【问题标题】:Getting django signals to work between applications让 django 信号在应用程序之间工作
【发布时间】:2020-11-11 19:30:38
【问题描述】:

我有一个名为receipt_printer 的Django 应用程序,它应该在使用信号接收到订单时打印订单。这里有两个应用程序分别称为:Ordersreceipt_printer

但是,无论何时处理订单并充满电,我都无法让信号正常工作。为简单起见,下面的示例只是将一些内容打印到控制台。如果我在 Orders 应用程序的 models.py 中执行所有操作,它就可以正常工作。

receipt_printer/apps.py

from django.apps import AppConfig

class ReceiptPrinterConfig(AppConfig):
    name = 'receipt_printer'

    def ready(self):
        from . import signals

receipt_printer/signals.py

from django.db import models
from saleor.order.models import Order
from django.db.models.signals import post_save

def order_fully_paid_signal(sender, instance, created, **kwargs):
    if instance.get_payment_status() == "fully-charged":
        print("This signal is working for fully paid order")
    else:
        print("This signal won't working for fully paid order")
post_save.connect(order_fully_paid_signal, sender=Order) 

receipt_printer/init.py

default_app_config = 'receipt_printer.apps.ReceiptPrinterConfig'

更新,也尝试了以下 - 没用:

@receiver(post_save, sender=Order)
def order_fully_paid_signal(sender, instance, created, **kwargs):
    if instance.get_payment_status() == "fully-charged":
        print("This signal is working for fully paid order")
    else:
        print("This signal won't working for fully paid order")

【问题讨论】:

  • receipt_printer/init.py 中是否有错字 - default_app_conig 而不是 default_app_config
  • 是的,抱歉,打错了,我会更正
  • 为清楚起见,错字仅在问题上。还是不行
  • 你可以试试下面的模式吗?您可能需要恢复对 apps.py 和 init.py 的更改

标签: python django django-signals saleor


【解决方案1】:

不完全确定问题出在哪里,但下面是我使用的 post_save 模式,它可以跨应用工作,无需对 apps.py 或 init.py 进行任何更改:

from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=<Model>, dispatch_uid='<model>_post_save')
def <model>_post_save(sender, instance, **kwargs):

    ...

【讨论】:

  • 我的型号名称的大小写是什么?例如:如果我有一个名为“BookCover”的模型怎么办?
  • 大小写无关,您可以随意命名您的函数 - 请注意,如果 dispatch_uid 不是唯一的,您可能会遇到问题,因此请确保它是唯一的。
【解决方案2】:

我需要在我的 models.py 底部为 Orders 应用添加以下行:

from saleor.saleor_package.receipt_printer.signals import order_fully_paid_signal

【讨论】:

  • 为什么要在模型中添加以下导入?
猜你喜欢
  • 1970-01-01
  • 2017-07-15
  • 1970-01-01
  • 1970-01-01
  • 2012-03-05
  • 1970-01-01
  • 2012-04-01
  • 1970-01-01
  • 2013-09-30
相关资源
最近更新 更多