为什么我的 Django 信号文件设置后不起作用?

问题描述 投票:0回答:1

我试图在买家完成付款后向卖家发送电子邮件,但我遇到了一些问题,并且电子邮件未发送。我添加了一个 print 语句和一个 try- except 块,以便我可以使用它来调试,但 print 语句没有在控制台中带来任何信息,并且 try 块也没有在控制台中返回任何成功或错误消息。请帮忙。 这是我的

signals.py
文件

# Stdlib Imports
import uuid

# Django Imports
from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver
from django.core.mail import send_mail
from django.conf import settings

# Own Imports
from payment.models import PaymentHistory


@receiver(pre_save, sender=PaymentHistory)
def create_ref_code_if_does_not_exist(sender, instance, **kwargs):
    """
    Creates a reference code that will be used by paysack;
    if one does not exist.
    """

    if not instance.ref_code:
        instance.ref_code = uuid.uuid4()


@receiver(post_save, sender=PaymentHistory)
def send_payment_notification_email(sender, instance, created, **kwargs):
    if created and instance.status == 'completed':
        print("PaymentNotificationEmail signal triggered.") # For debugging 
        # PaymentHistory model has a ForeignKey to the BuyerOrderHistory model
        buyer_order = instance.order

        # BuyerOrderHistory has a ForeignKey to the Product model
        product = buyer_order.product

        # Get the seller's email address and name
        seller_email = product.user.email
        seller_name = product.user.full_name  

        # Compose the email subject and message
        subject = 'Product Payment Notification'
        message = f'Hello {seller_name},\n\n'
        message += f'The product "{product.title}" has been paid for.\n'
        message += f'Amount Paid: {instance.amount}\n\n'
        message += 'Log in to your account to manage the order.'

        # Send the email
        try:
            send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [seller_email])
            print("Email sent successfully.")
        except Exception as e:
            print(f"Error sending email: {e}")

我的

apps.py
文件看起来像这样

from django.apps import AppConfig


class PaymentConfig(AppConfig):
    default_auto_field = "django.db.models.BigAutoField"
    name = "payment"

    def ready(self):
        """Import payment signals when app load."""
        import payment.signals


这是我的

payment/models.py
文件:

class PaymentHistory(ObjectTracker):
    user_email = models.EmailField(
        max_length=255, help_text="THe user email address.", editable=False
    )
    order = models.ForeignKey(
        BuyerOrderHistory,
        on_delete=models.DO_NOTHING,
        help_text="The order on-which the payment action was initiated for.",
    )
    amount = models.FloatField(
        help_text="The naira amount of the payment.", null=True, blank=True
    )
    status = models.CharField(
        choices=PaymentStatus.choices, default="pending", max_length=100
    )
    remark = models.CharField(
        max_length=300, help_text="What is this payment transaction for?"
    )

状态字段有一个默认值,该值是待定的,但当买家完成交易并经过验证时,该值将更新为“已完成”。

我的

settings.py
已安装该应用程序

INSTALLED_APPS = [
    ...
    "payment",
    ...
]

我尝试运行代码,操作成功,但信号文件中的电子邮件未发送。就好像我的信号文件根本没有被触发。

python django django-rest-framework django-signals
1个回答
0
投票

Django 不会立即加载名为

signals.py
的文件。您需要强制加载它。通常,这是在
AppConfig
中完成的:

# payment/apps.py

from django.apps import AppConfig


class PaymentConfig(AppConfig):
    def ready(self):
        import payment.signals  # noqa
© www.soinside.com 2019 - 2024. All rights reserved.