from django.db.models.signals import m2m_changed from django.dispatch import receiver from .models import Card @receiver(m2m_changed, sender=Card.decks.through) def update_card_style(sender, instance, action, **kwargs): if action == "post_add": decks = instance.decks.all() num_decks = decks.count() if num_decks == 1: instance.style = "background-color: " + decks.first().hex_color + ";" elif num_decks >= 2: hex_colors = [deck.hex_color for deck in decks] instance.style = f"background: linear-gradient(to right, {', '.join(hex_colors)});" else: instance.style = "background: linear-gradient(to right, #AAAAAA, #AAAAAA, #AAAAAA);" instance.save(update_fields=["style"])