为什么Django模型信号不工作?

atmip9wb  于 2022-12-14  发布在  Go
关注(0)|答案(5)|浏览(161)

我正在尝试从用户的状态创建他们的活动流。
型号:

class Status(models.Model):
    body = models.TextField(max_length=200)
    image = models.ImageField(blank=True, null=True, upload_to=get_upload_file_name)
    privacy = models.CharField(max_length=1,choices=PRIVACY, default='F')
    pub_date = models.DateTimeField(auto_now_add=True, auto_now=False)
    user = models.ForeignKey(User)

class Activity(models.Model):
    actor = models.ForeignKey(User)
    action = models.CharField(max_length=100)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')
    pub_date = models.DateTimeField(auto_now_add=True, auto_now=False)

但是,虽然我创建了一个新的状态,但它并没有从post_save信号创建一个新的活动。
信号:

from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import post_save
from status.models import Status
from models import Activity

def create_activity_item(sender, instance, signal, *args, **kwargs):
    if kwargs.get('created', True):
        ctype = ContentType.objects.get_for_model(instance)

        if ctype.name == 'Status':
            action = ' shared '

            activity = Activity.objects.get_or_create(
                actor = instance.user,
                action = action,
                content_type = ctype,
                object_id = instance.id,
                pub_date = instance.pubdate
            )

post_save.connect(create_activity_item, sender=Status)

我做错了什么?请帮我解决这个问题。我会非常感激的。谢谢。

更新日期:

然而,这样做会产生活动:

@receiver(post_save, sender=Status)
def create(sender, instance, **kwargs):
    if kwargs.get('created',True):
        ctype = ContentType.objects.get_for_model(instance)
        activity = Activity.objects.get_or_create(
            actor = instance.user,
            action = ' shared ',
            content_type = ctype,
            object_id = instance.id,
            pub_date = instance.pub_date
        )

为什么上面的方法行不通呢?

kognpnkq

kognpnkq1#

看起来你的post_save.connect没有被执行。你应该在某个地方导入signals。对于django 1.7,建议在应用的config ready()函数中导入。请阅读文档中的“此代码应该位于何处?”注解。
例如,如果您的应用名为activity

活动/初始化.py

default_app_config = 'activity.apps.ActivityAppConfig'

活动/apps.py

from django.apps import AppConfig

class ActivityAppConfig(AppConfig):
    name = 'activity'

    def ready(self):
        import activity.signals

不要忘记将dispatch_uid添加到connect()调用中:

post_save.connect(create_activity_item, sender=Status,
                  dispatch_uid="create_activity_item")

UPDATEContentTypename属性始终为小写。因此,应将if语句更改为:

if ctype.name == 'status':
2skhul33

2skhul332#

假设您的应用程序名称为blog,在settings.py您项目的www.example.com文件中,确保将主项目settings.py文件的INSTALLED_APP变量中的blog应用程序注册为blog.apps.BlogConfig,而不仅仅是blog

iecba09b

iecba09b3#

如果您在signals.py中正确写入了所有内容,但无法正常工作,请检查以下步骤...(假设在名为AppName的应用程序中)
1.在__init__.py中,将行

default_app_config = 'AppName.apps.AppnameConfig'

1.在apps.py文件中,将块

from django.apps import AppConfig

class AppnameConfig(AppConfig):
    name = 'AppName'

    def ready(self):
        import AppName.signals
wyyhbhjk

wyyhbhjk4#

不接触apps.py,这对我很有效。

class MyModel(models.Model):
    """ MyModel fields go """
    body = models.TextField(max_length=200)
    pub_date = models.DateTimeField(auto_now_add=True, auto_now=False)

def post_save_actions(sender, instance, created, **kwargs):
    if created:
        pass
        # post save actions if new instance is created,
        # do something with `instance` or another models
        # be careful about circular imports. \m/

并且信号钩住,

post_save.connect(post_save_user_actions, sender=MyModel)
4xy9mtcn

4xy9mtcn5#

简单、可扩展、可重复、可重用的答案是...
如果您计划使用信号(例如:signals.py)(例如:posts),只需养成每次**都将其添加到apps.py**的习惯。

def ready(self):
    from . import signals

你不需要像其他人说的那样触摸__init__.py,你的信号就会起作用。

相关问题