模型:
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
)
为什么上述方法不起作用?
__init__.py
文件中,我添加了default_app_config = 'activities.apps.ActivityAppConfig'
,因为activities
是应用程序的名称。然后,在该应用程序中添加了一个新的apps.py
文件,并将ActivityAppConfig
的名称字段更改为“activities”。最后,添加了dispatch_uid
。 - Kakarimport activity.signals
没有被使用,但不要被愚弄了,因为Django确实需要它来使信号在你的模型中工作。这个答案让我省了几个小时的压力。谢谢。 - ivanleoncz