[英]Object needs to have a value for field “id” before this many-to-many relationship can be used in Django
[英]django "<User: user556>" needs to have a value for field "id" before this many-to-many relationship can be used
我正在尝试保存 M2M object (将其设置为默认值,即 id = 1 的值)。
我收到以下错误的问题:
"<User: user556>" 需要有一个字段 "id" 的值才能使用这种多对多关系。
我查看了涵盖相同错误的先前提要,但没有人解释它发生在 form_valid function 中,因为它发生在我身上
我的代码如下:
def form_valid(self,form):
instance = form.instance
instance.groups.set(1)
instance.save()
return super(UserCreateView,self).form_valid(form)
您首先需要保存您的实例,使其具有主键,否则您无法在联结表中创建记录。
因此,您可以通过以下方式实现:
from django.http import HttpResponseRedirect
def form_valid(self,form):
instance = form.save()
instance.groups.set(1)
return HttpResponseRedirect(self.get_success_url())
此处返回HttpResponseRedirect
是必要的,因为super().form_valid()
会将表单再次保存到数据库中,并且还会将groups
设置为表单中指定的组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.