Django:模型上缺少外部信号回调函数
嘿, 我试图让信号 pre_save 在我的模型上工作,但是有 似乎是外键或其他问题。我的模型是 像这样:
class BlogEntry(models.Model):
headline = models.CharField(max_length=100)
content = models.CharField(max_length=2000)
written_by = models.ForeignKey(User)
date = models.DateTimeField(auto_now=True)
project = models.ForeignKey(Project)
这是处理和保存表单的地方:
def form_valid(self, blogform): # post a blogentry
blog_entry = blogform.save(commit=False)
blog_entry.written_by = self.request.user
blog_entry.project = blog_entry.project #debugging shows that this
is a valid instance of the Project model
blog_entry.save()
return TemplateResponseMixin.render_to_response(self,
self.get_context_data())
这是我的信号接收器函数
@receiver(post_save, sender=BlogEntry)
def project_blog_entry_signal(sender, **kwargs):
log = Log()
log.project = sender.project.field
log.content_type = Log.content_new_blogentry
log.save()
这是例外:
<块引用>无法分配 “django.db.models.fields.lated.ForeignKey 对象位于 0x21eef86c": "Log.project" 必须是“项目”实例。
@线--->日志.项目 = sender.project.field 位于
<块引用>project_blog_entry_signal() 函数
发送者对象似乎没有将项目作为模型实例传递,而是作为外键实例传递。这是为什么?
Hey,
Im trying to get the signal pre_save to work on my model but there
seems to be some problem with a foreign key or something. My model is
like this:
class BlogEntry(models.Model):
headline = models.CharField(max_length=100)
content = models.CharField(max_length=2000)
written_by = models.ForeignKey(User)
date = models.DateTimeField(auto_now=True)
project = models.ForeignKey(Project)
And here is where the form is processed and saved:
def form_valid(self, blogform): # post a blogentry
blog_entry = blogform.save(commit=False)
blog_entry.written_by = self.request.user
blog_entry.project = blog_entry.project #debugging shows that this
is a valid instance of the Project model
blog_entry.save()
return TemplateResponseMixin.render_to_response(self,
self.get_context_data())
And here's my signal reciever function
@receiver(post_save, sender=BlogEntry)
def project_blog_entry_signal(sender, **kwargs):
log = Log()
log.project = sender.project.field
log.content_type = Log.content_new_blogentry
log.save()
And here's the exception:
Cannot assign
"django.db.models.fields.related.ForeignKey
object at 0x21eef86c": "Log.project"
must be a "Project" instance.@the line ---> log.project =
sender.project.field inproject_blog_entry_signal() function
The sender object doesn't seem to pass the project as a model instance but rather as a Foreign key instance. Why is that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
解决了。 “sender”参数只是一个类对象,而不是一个实例。在我的回调中,我可以通过 kwargs 引用实例,例如:
blog_entry_instance = kwargs["instance"]
因此回调函数将如下所示:
Solved it. The 'sender' argument is just a class object, not an instance. In my callback I can reference the instance by the kwargs like:
blog_entry_instance = kwargs["instance"]
So the callback function would look like this: