【问题标题】:django "<User: user556>" needs to have a value for field "id" before this many-to-many relationship can be useddjango "<User: user556>" 需要有一个字段 "id" 的值才能使用这种多对多关系
【发布时间】:2021-05-12 10:49:04
【问题描述】:

我正在尝试保存一个 M2M 对象(将其设置为默认值,即 id = 1 的那个)。

我收到以下错误的问题:

”需要有字段“id”的值才能使用这种多对多关系。

我查看了以前的提要,其中涵盖了相同的错误,但没有人解释它何时发生在 form_valid 函数中,因为它发生在我身上

我的代码如下:

  def form_valid(self,form):

    instance = form.instance
    instance.groups.set(1)
    instance.save()
    return super(UserCreateView,self).form_valid(form)

【问题讨论】:

  • 您必须将instance.save() 行放在instance.groups.set(1) 行之上。

标签: python django django-views


【解决方案1】:

您首先需要保存您的实例,使其具有主键,否则您无法在联结表中创建记录。

因此,您可以使用:

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 设置为表单中指定的值。

【讨论】:

  • 如果你愿意的话,有一种叫super().form_valid() 的有点笨拙的方法(在别人的回答中看到了这个)。类似于response = super().form_valid() # your code return response
  • 您好,感谢该对象现在正在保存,但组字段尚未设置它为空,可能是 set 方法的问题?
  • @nassim: 你确定有id=1 的群组吗?如果您打印print(instance.groups.all()) 会怎样。此外,如上所述,您需要删除 super().form_valid() 调用。
  • 谢谢我解决了问题是我使用自定义组并调用 instance.groups 调用默认的 django 组所以我不得不将其更改为 instance.appname_groups (数据库中的字段名称) 并且它起作用了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-08
  • 1970-01-01
  • 2013-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多