/ posts / 12 / new-comment / NOT NULL约束处的IntegrityError失败:posts_comment.author_id

时间:2020-10-15 19:35:43

标签: python django django-models django-views django-templates

好吧,我在项目中添加了评论系统,但是出现了完整性错误。我不知道该怎么解决。我已经问过这个问题一次,但现在已经回答了。但是现在我再问一次,希望有人能详细回答。我将非常感谢您。

view.py

class CommentCreateView(CreateView):
    redirect_field_name='posts/post_detail.html' 
    model = Comment
    form_class = CommentForm
    template_name = "posts/snippets/comment_form.html"

    def form_valid(self, form):
        form.instance.post_id = self.kwargs['pk']
        return super().form_valid(form)

models.py

class Comment(models.Model):

    
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post,related_name='comments', on_delete=models.CASCADE)
    body = models.TextField()
    create_date = models.DateTimeField(auto_now_add=True)


    def __str__(self):
        return self.author.username

    def get_absolute_url(self):
        return reverse("posts:post_detail", kwargs={"pk": self.pk})

回溯:

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/posts/12/new-comment/

Django Version: 3.0.3
Python Version: 3.8.3
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'bootstrap3',
 'accounts',
 'posts',
 'profiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



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

The above exception (NOT NULL constraint failed: posts_comment.author_id) was the direct cause of the following exception:
  File "C:\Users\AHMED\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\AHMED\anaconda3\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\AHMED\anaconda3\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\AHMED\anaconda3\lib\site-packages\django\views\generic\base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\AHMED\anaconda3\lib\site-packages\django\views\generic\base.py", line 97, in dispatch
    return handler(request, *args, **kwargs)
  File "C:\Users\AHMED\anaconda3\lib\site-packages\django\views\generic\edit.py", line 172, in post
    return super().post(request, *args, **kwargs)
  File "C:\Users\AHMED\anaconda3\lib\site-packages\django\views\generic\edit.py", line 142, in post
    return self.form_valid(form)
  File "C:\Users\AHMED\grapPub\grabpublic\posts\views.py", line 74, in form_valid
    return super().form_valid(form)
  File "C:\Users\AHMED\anaconda3\lib\site-packages\django\views\generic\edit.py", line 125, in form_valid
    self.object = form.save()
  File "C:\Users\AHMED\anaconda3\lib\site-packages\django\forms\models.py", line 459, in save
    self.instance.save()
  File "C:\Users\AHMED\anaconda3\lib\site-packages\django\db\models\base.py", line 745, in save
    self.save_base(using=using, force_insert=force_insert,
  File "C:\Users\AHMED\anaconda3\lib\site-packages\django\db\models\base.py", line 782, in save_base
    updated = self._save_table(
  File "C:\Users\AHMED\anaconda3\lib\site-packages\django\db\models\base.py", line 887, in _save_table
    results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
  File "C:\Users\AHMED\anaconda3\lib\site-packages\django\db\models\base.py", line 924, in _do_insert
    return manager._insert(
  File "C:\Users\AHMED\anaconda3\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\AHMED\anaconda3\lib\site-packages\django\db\models\query.py", line 1204, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
  File "C:\Users\AHMED\anaconda3\lib\site-packages\django\db\models\sql\compiler.py", line 1384, in execute_sql
    cursor.execute(sql, params)
  File "C:\Users\AHMED\anaconda3\lib\site-packages\django\db\backends\utils.py", line 100, in execute
    return super().execute(sql, params)
  File "C:\Users\AHMED\anaconda3\lib\site-packages\django\db\backends\utils.py", line 68, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "C:\Users\AHMED\anaconda3\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "C:\Users\AHMED\anaconda3\lib\site-packages\django\db\backends\utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\AHMED\anaconda3\lib\site-packages\django\db\utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\Users\AHMED\anaconda3\lib\site-packages\django\db\backends\utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\AHMED\anaconda3\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute
    return Database.Cursor.execute(self, query, params)

Exception Type: IntegrityError at /posts/12/new-comment/
Exception Value: NOT NULL constraint failed: posts_comment.author_id

如果需要更多细节,请告诉我。我将使用该信息更新答案。

2 个答案:

答案 0 :(得分:1)

您需要将登录用户分配为作者:

from django.contrib.auth.mixins import LoginRequiredMixin

class CommentCreateView(LoginRequiredMixin, CreateView):
    redirect_field_name='posts/post_detail.html' 
    model = Comment
    form_class = CommentForm
    template_name = "posts/snippets/comment_form.html"

    def form_valid(self, form):
        form.instance.post_id = self.kwargs['pk']
        form.instance.author = self.request.user
        return super().form_valid(form)

Comment类的.get_absolute_url(…) method [Django-doc]中也存在错误,因为您使用的是帖子的详细信息页面,所以pk参数应该是{{ 1}}对象,因此您可以使用post

self.post_id

注意:您可以将视图限制为基于类的视图,以使用 LoginRequiredMixin mixin [Django-doc]


注意:与直接使用settings.AUTH_USER_MODEL [Django-doc]相比,通常最好使用User model [Django-doc]来引用用户模型。有关更多信息,请参见referencing the User model section of the documentation

答案 1 :(得分:1)

您应该在验证表单数据之前对其进行设置,并且还应该在其中设置author ID

class CommentCreateView(LoginRequiredMixin, CreateView):
  redirect_field_name='posts/post_detail.html' 
  model = Comment
  form_class = CommentForm
  template_name = "posts/snippets/comment_form.html"

  def get_form_kwargs(self):
    kwargs = super().get_form_kwargs()
    kwargs['post']= self.kwargs['pk']
    kwargs['author']= self.request.user.id
    return kwargs