简体   繁体   中英

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

I don't know why the error is caused even though I designated the author. I'd appreciate your help.

model & form

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']

views.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()
...

在此处输入图像描述

return IntegrityError at /polls/debate/create/ NOT NULL constraint failed: polls_supertitle.author_id

You get this error becouse you want to save form(create new SuperTitle objetd in database) without author. You need to pass author objectd or id somehow to form. If the request.user is author i recommend form:

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

and in view:

    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}
...

Probably you don't have authenticated user so that request.user is returning None.

Make use of login_required decorator so that only the authenticated user can access this function.


from django.contrib.auth.decorators import login_required

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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