IntegrityError NOT NULL constraint failed: even though I have already overriden the form_valid?

So I’m trying to create a simple Comment feature for a blog app. In the Class-based views, if you are using a Foreign Key in your model, I know that you have to override the def form_valid: in order for the Comment to be posted by the current logged-in User. If you don’t, you get the IntegrityError

I did this for the Blog model in my app, and it works just as intended, however, when I try to do the same with the CommentCreateView, I get the error.

Here’s my code so far

views.py

class IssueCreateView(LoginRequiredMixin, CreateView):
    model = Issue
    fields = ['title', 'content', 'mark_as', 'assignee', 'priority', 'label']

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

class CommentCreateView(LoginRequiredMixin, CreateView):
    model = Comment
    fields = ['title', 'content']
    template_name = 'issues/add_comment.html'

    def form_valid(self, form):
        form.instance.name = self.request.user
        return super().form_valid(form)

models.py

class Comment(models.Model):
    issue = models.ForeignKey(Issue,
                              on_delete=models.CASCADE, 
                              related_name='comments')
    
    name = models.ForeignKey(User, on_delete=models.CASCADE) 
    title = models.CharField(max_length=100, null=True)
    content = models.TextField()
    date = models.DateTimeField(auto_now_add=True)
    
    def __str__(self):
        return self.title
    def get_absolute_url(self):
        return reverse('issue-detail', kwargs={'pk': self.pk})
class Issue(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    
    def __str__(self):
        return self.title


    def get_absolute_url(self):
        return reverse('issue-detail', kwargs={'pk': self.pk})

What did I do wrong?

Traceback

Traceback (most recent call last):
  File "C:\Users\mikha\bug_env\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\mikha\bug_env\lib\site-packages\django\db\backends\sqlite3\base.py", line 416, in execute
    return Database.Cursor.execute(self, query, params)

The above exception (NOT NULL constraint failed: issues_comment.issue_id) was the direct cause of the following exception:
  File "C:\Users\mikha\bug_env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\mikha\bug_env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\mikha\bug_env\lib\site-packages\django\views\generic\base.py", line 69, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\mikha\bug_env\lib\site-packages\django\contrib\auth\mixins.py", line 71, in dispatch
    return super().dispatch(request, *args, **kwargs)
  File "C:\Users\mikha\bug_env\lib\site-packages\django\views\generic\base.py", line 101, in dispatch
    return handler(request, *args, **kwargs)
  File "C:\Users\mikha\bug_env\lib\site-packages\django\views\generic\edit.py", line 174, in post
    return super().post(request, *args, **kwargs)
  File "C:\Users\mikha\bug_env\lib\site-packages\django\views\generic\edit.py", line 144, in post
    return self.form_valid(form)
  File "C:\Users\mikha\bug_app\issues\views.py", line 101, in form_valid
    return super().form_valid(form)
  File "C:\Users\mikha\bug_env\lib\site-packages\django\views\generic\edit.py", line 127, in form_valid
    self.object = form.save()
  File "C:\Users\mikha\bug_env\lib\site-packages\django\forms\models.py", line 466, in save
    self.instance.save()
  File "C:\Users\mikha\bug_env\lib\site-packages\django\db\models\base.py", line 743, in save
    self.save_base(using=using, force_insert=force_insert,
  File "C:\Users\mikha\bug_env\lib\site-packages\django\db\models\base.py", line 780, in save_base
    updated = self._save_table(
  File "C:\Users\mikha\bug_env\lib\site-packages\django\db\models\base.py", line 885, in _save_table
    results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
  File "C:\Users\mikha\bug_env\lib\site-packages\django\db\models\base.py", line 923, in _do_insert
    return manager._insert(
  File "C:\Users\mikha\bug_env\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\mikha\bug_env\lib\site-packages\django\db\models\query.py", line 1301, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
  File "C:\Users\mikha\bug_env\lib\site-packages\django\db\models\sql\compiler.py", line 1441, in execute_sql
    cursor.execute(sql, params)
  File "C:\Users\mikha\bug_env\lib\site-packages\django\db\backends\utils.py", line 99, in execute
    return super().execute(sql, params)
  File "C:\Users\mikha\bug_env\lib\site-packages\django\db\backends\utils.py", line 67, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "C:\Users\mikha\bug_env\lib\site-packages\django\db\backends\utils.py", line 76, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "C:\Users\mikha\bug_env\lib\site-packages\django\db\backends\utils.py", line 80, in _execute
    with self.db.wrap_database_errors:
  File "C:\Users\mikha\bug_env\lib\site-packages\django\db\utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\Users\mikha\bug_env\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\mikha\bug_env\lib\site-packages\django\db\backends\sqlite3\base.py", line 416, in execute
    return Database.Cursor.execute(self, query, params)

Please post the complete error message with the traceback - it will identify which field is not being specified. (It looks like you’re not supplying a reference to the Post object that the comment is supposed to relate to, but that’s just a guess at this point.)

Edited with full error message and traceback

I do believe my guess is correct. Your Comment model has a field issue as a ForeignKey to Issue. But that field is not in the form and not being set by the view. That is the field throwing the error, not the name field.

1 Like

I corrected the views file to set the issue field. But then I get this error.

views.py

class CommentCreateView(LoginRequiredMixin, CreateView):
    model = Comment
    fields = ['title', 'content']
    template_name = 'issues/add_comment.html'

    def form_valid(self, form):
        form.instance.issue = self.request.user
        return super().form_valid(form)

    

Traceback (most recent call last):
  File "C:\Users\mikha\bug_env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\mikha\bug_env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\mikha\bug_env\lib\site-packages\django\views\generic\base.py", line 69, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\mikha\bug_env\lib\site-packages\django\contrib\auth\mixins.py", line 71, in dispatch
    return super().dispatch(request, *args, **kwargs)
  File "C:\Users\mikha\bug_env\lib\site-packages\django\views\generic\base.py", line 101, in dispatch
    return handler(request, *args, **kwargs)
  File "C:\Users\mikha\bug_env\lib\site-packages\django\views\generic\edit.py", line 174, in post
    return super().post(request, *args, **kwargs)
  File "C:\Users\mikha\bug_env\lib\site-packages\django\views\generic\edit.py", line 144, in post
    return self.form_valid(form)
  File "C:\Users\mikha\bug_app\issues\views.py", line 100, in form_valid
    form.instance.issue = self.request.user
  File "C:\Users\mikha\bug_env\lib\site-packages\django\db\models\fields\related_descriptors.py", line 215, in __set__
    raise ValueError(

Exception Type: ValueError at /issue/1/comment
Exception Value: Cannot assign "<SimpleLazyObject: <User: miko>>": "Comment.issue" must be a "Issue" instance.

What does it mean?

What is the error message telling you? What do you think it means?