Как я могу создать правильные m2m сигналы в Django для получения уведомлений?

Я хочу создать сигнал для ProductREVIEWS, чтобы когда пользователь оставляет отзыв о конкретном продукте, продавец получал уведомление типа "пользователь оставил отзыв о вашем продукте". Я создал сигнал, но он не сработал. Пожалуйста, проверьте это и дайте мне соответствующее решение.

signals.py:

@receiver(m2m_changed, sender = ProductREVIEWS.product)
def send_notification_when_someone_give_feedback(instance, pk_set, action, *args, **kwargs):
    pk = list(pk_set)[0]
    user = User.objects.get(pk=pk)

    if action == "post_add":
        Notification.objects.create(
            content_object = instance,
            user = instance.user,
            text = f"{user.username} given feedback on your product.",
            notification_types = "ProductREVIEWS"
        )

models.py:

class Products(models.Model):
    user = models.ForeignKey(User, related_name="merchandise_product_related_name", on_delete=models.CASCADE, blank=True, null=True)
    product_title = models.CharField(blank=True, null=True, max_length = 250)


class ProductREVIEWS(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='userREVIEW',on_delete=models.CASCADE)
    product = models.ForeignKey(Products, related_name='productREVIEWrelatedNAME',on_delete=models.CASCADE)
    feedBACK = models.TextField(blank=True, null=True)

views.py:

def user_notifications(request):
    notifications = Notification.objects.filter(
        user = request.user,
        is_seen = False
    )
    for notification in notifications:
        notification.is_seen = True
        notification.save()
    return render(request, 'notifications.html')

context_processors.py:

from notification.models import Notification

def user_notifications(request):
    context = {}

    if request.user.is_authenticated:
        notifications = Notification.objects.filter(
            user = request.user
        ).order_by('-created_date')

        unseen = notifications.exclude(is_seen = True)
        context['notifications'] = notifications
        context['unseen'] = unseen.count()
    return context

templates:

{% if notification.notification_types == 'ProductREVIEWS' %}
          <a href="{% url 'quick_view' notification.content_object.id %}">
              {{ notification.text }}
          </a>
{% endif %}

Вы делаете ошибку, потому что это signal относится к m2m relation.

Отправляется при изменении поля ManyToManyField в экземпляре модели.

В вашем случае, если вы хотите использовать signals, посмотрите на post_save или pre_save.

@receiver(post_save, sender=ProductREVIEWS)
def send_notification_when_someone_give_feedback(sender, instance, **kwargs):
    if feedback:
        # create notification, send email or what you want
Вернуться на верх