Python /posts/12/new comment/NOT NULL约束处的IntegrityError失败:posts\u comment.author\u id

Python /posts/12/new comment/NOT NULL约束处的IntegrityError失败:posts\u comment.author\u id,python,django,django-models,django-views,django-templates,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 templ

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

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

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

您需要将登录用户指定为作者:

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)

注意:您可以将基于类的视图限制为具有


注意:通常最好使用来引用用户模型,而不是直接使用。有关更多信息,请参见


您应该在验证表单数据之前设置表单数据,还应该在那里设置
author
ID

class CommentCreateView(LoginRequiredMixin,CreateView):
重定向\u字段\u name='posts/post\u detail.html'
模型=注释
form_class=CommentForm
template\u name=“posts/snippets/comment\u form.html”
def get_form_kwargs(自我):
kwargs=super()
kwargs['post']=self.kwargs['pk']
kwargs['author']=self.request.user.id
返回kwargs

它正在工作,但它正在其他帖子上重定向我。不是在我要评论的帖子上。@FlashMaddy:是的,应该是
self.post\u id
get\u absolute\u url
中,请参见编辑。我刚刚将
author=models.ForeignKey(User,on\u delete=models.CASCADE)
更改为
author=models.ForeignKey(UserProfile,on\u delete=models.CASCADE)
当我再次尝试注释时,它显示了一个错误:ValueError at/posts/12/new comment/无法分配“”:“comment.author”必须是“UserProfile”实例。@FlashMaddy:那么您的用户模型很可能是
UserProfile
。因此,在这种情况下,拥有
用户
模型就没有多大意义了。请参阅。@FlashMaddy:一个用户通常会创建一个自定义用户模型,或者使用一个额外的
UserProfile
模型(但在这种情况下,您通常不会将其作为用户模型)。是的,它不会修复完整性错误,但会在其他帖子上重定向我。不要在我评论的帖子上重定向我,我问了一个新问题,你可以看看你是否能回答
class Comment(models.Model):
    # …
    
    def get_absolute_url(self):
        return reverse('posts:post_detail', kwargs={'pk': self.post_id})