Home > Software engineering >  django.db.utils.IntegrityError: NOT NULL constraint failed: user.id
django.db.utils.IntegrityError: NOT NULL constraint failed: user.id

Time:08-07

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

enter image description here

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

CodePudding user response:

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

CodePudding user response:

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):
   ........
  • Related