繁体   English   中英

django.db.utils.IntegrityError: NOT NULL 约束失败:user.id

[英]django.db.utils.IntegrityError: NOT NULL constraint failed: user.id

即使我指定了作者,我也不知道为什么会导致错误。 我会很感激你的帮助。

model & 表格

class SuperTitle(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='debate_author')
    super_title = models.CharField(max_length=100)
    liker = models.ManyToManyField(User, related_name='debate_liker')

    def __str__(self):
        return self.super_title


class SuptitForm(forms.ModelForm):
    class Meta:
        model = SuperTitle
        fields = ['super_title']

视图.py

def create(request):
...
  dic = {'super_title' : request.POST.get('sup_title')}
  sup_form = SuptitForm(dic)
  if sup_form.is_valid():
    sup_form.author = request.user
    sup_form.super_title = ...
    sup_form.save()
...

在此处输入图像描述

在 /polls/debate/create/ NOT NULL 约束返回 IntegrityError 失败:polls_supertitle.author_id

您会收到此错误,因为您想在没有作者的情况下保存表单(在数据库中创建新的 SuperTitle 对象)。 您需要以某种方式传递作者反对或 id 来形成。 如果 request.user 是作者,我推荐表格:

class SuptitForm(forms.ModelForm):
    class Meta:
        model = SuperTitle
        fields = ['super_title', 'author']
        widgets = {'author': forms.HiddenInput()}

并认为:

    def create(request):
      if request.method == 'POST':
        sup_form = SuptitForm(request.POST)
        if sup_form.is_valid():
          sup_form.save()
      else:
        sup_form = SuptitForm(initial={'author': request.user}
...

可能您没有经过身份验证的用户,因此request.user返回无。

使用login_required装饰器,以便只有经过身份验证的用户才能访问此 function。


from django.contrib.auth.decorators import login_required

@login_required
def create(request):
   ........

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM