gpt4 book ai didi

django 信号未按预期工作

转载 作者:行者123 更新时间:2023-12-04 10:52:07 30 4
gpt4 key购买 nike

我正在尝试创建一个项目,在 blog 的帮助下创建用户的提要/事件提要.

这些是模型 -

class StreamItem(models.Model):
user = models.ForeignKey(User)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
pub_date = models.DateTimeField(default=datetime.now)
content_object = generic.GenericForeignKey('content_type', 'object_id')

@property
def content_class(self):
return self.content_type.model


class Blog(models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length=300)
body = models.TextField()
pub_date = models.DateTimeField(default=datetime.now)


class Photo(models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length=200)
image = models.ImageField(upload_to=get_upload_file_name)
pub_date = models.DateTimeField(default=datetime.now)

这是signals.py:
__init__.py
from django.db.models import signals
from django.contrib.contenttypes.models import ContentType
from django.dispatch import dispatcher
from blogs.models import Blog
from picture.models import Photo
from models import StreamItem

def create_stream_item(sender, instance, signal, *args, **kwargs):

# Check to see if the object was just created for the first time

if 'created' in kwargs:
if kwargs['created']:
create = True

# Get the instance's content type

ctype = ContentType.object.get_for_model(instance)

if create:
si = StreamItem.objects.get_or_create(user=instance.user, content_type=ctype, object_id=instance.id, pub_date = instance.pub_date)

# Send a signal on post_save for each of these models

for modelname in [Blog, Photo]:
dispatcher.connect(create_stream_item, signal=signals.post_save, sender=modelname)

当我创建博客或上传照片时, signal不起作用。而且我也没有收到任何错误。但我可以手动将项目添加到 StreamItem使用管理员的应用程序,并且 StreamItem 确实可以按我的意愿工作。我认为signals.py有问题。请帮帮我。将不胜感激。谢谢你。

最佳答案

您必须确保在 django 启动后立即加载信号。
确保它的一种可能方法是将模块导入 __init__.py

# __init__.py
# add the below line and run the project again
import signals

关于django 信号未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20274920/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com