pkmntrade.club/trades/signals.py

22 lines
No EOL
957 B
Python

from django.core.exceptions import ValidationError
from django.db.models.signals import m2m_changed
from django.dispatch import receiver
from .models import TradeOffer
from cards.models import Card
def check_trade_offer_rarity(instance):
combined_cards = list(instance.have_cards.all()) + list(instance.want_cards.all())
# Use the normalized rarity from each card
rarities = {card.normalized_rarity for card in combined_cards}
if len(rarities) > 1:
raise ValidationError("All cards in a trade offer must have the same rarity.")
@receiver(m2m_changed, sender=TradeOffer.have_cards.through)
def validate_have_cards_rarity(sender, instance, action, **kwargs):
if action == "post_add":
check_trade_offer_rarity(instance)
@receiver(m2m_changed, sender=TradeOffer.want_cards.through)
def validate_want_cards_rarity(sender, instance, action, **kwargs):
if action == "post_add":
check_trade_offer_rarity(instance)