![](/img/trans.png)
[英]NOT NULL constraint failed: posts_comment.post_id django
[英]How to set post_id to resolve error : 'django.db.utils.IntegrityError: NOT NULL constraint failed: posts_comment.post_id'?
好吧,我正在使用 django,我正在尝试使用 ajax 添加评论。 当我单击未执行任何操作但在终端中的评论提交按钮时,它向我显示“django.db.utils.IntegrityError:NOT NULL 约束失败:posts_comment.post_id”错误。 我已经仔细检查了我的models.py,但仍然不知道如何解决它。
模型.py
class Comment(MPTTModel):
author = models.ForeignKey(User, related_name='author',
on_delete=models.CASCADE, default=None, blank=True)
parent = TreeForeignKey('self', on_delete=models.CASCADE,
null=True, blank=True, related_name='children')
post = models.ForeignKey(Post ,related_name='comments', on_delete=models.CASCADE)
body = models.TextField()
create_date = models.DateTimeField(auto_now_add=True)
status = models.BooleanField(default=True)
查看.py
def single_post(request ,*args, **kwargs):
slug=kwargs.get('slug')
print(slug,'slug')
pk=kwargs.get('pk')
print(pk,'pk')
post = get_object_or_404(Post,pk=pk,slug=slug)
allcomments = post.comments.filter(status=True)
comment_form = CommentForm()
return render(
request,
'posts/post_test.html',
{ 'post': post,
'comment_form': comment_form,
'allcomments': allcomments,
}
)
def addcomment(request):
if request.method == 'POST':
comment_form = CommentForm(request.POST)
print(comment_form)
if comment_form.is_valid():
user_comment = comment_form.save(commit=False)
result = comment_form.cleaned_data.get('body')
user = request.user.username
user_comment.author = request.user
user_comment.save()
return JsonResponse({'result2': result, 'user': user})
网址.py
urlpatterns = [
path('test/<int:pk>/<str:slug>/',views.single_post,name ='post_detail'),
path('commented/',views.addcomment,name='addcomment'),
]
如果需要更多信息而不是在评论会话中告诉我。 我会用这些信息更新我的问题。 谢谢 !
好吧,我已将我的 url 表单path('commented/',views.addcomment,name='addcomment'),
为path('commented/<int:pk>/<str:slug>/',views.addcomment,name='addcomment'),
比我还更新了添加评论功能
查看.py
def addcomment(request):
if request.method == 'POST':
comment_form = CommentForm(request.POST)
print(comment_form)
if comment_form.is_valid():
user_comment = comment_form.save(commit=False)
result = comment_form.cleaned_data.get('body')
user = request.user.username
user_comment.author = request.user
user_comment.save()
return JsonResponse({'result2': result, 'user': user})
到:views.py
def addcomment(request,*args, **kwargs):
slug=kwargs.get('slug')
print(slug,'slug')
pk=kwargs.get('pk')
print(pk,'pk')
print(request,'request')
post = get_object_or_404(Post,pk=pk,slug=slug)
if request.method == 'POST':
comment_form = CommentForm(request.POST)
print(comment_form,'postting')
if comment_form.is_valid():
user_comment = comment_form.save(commit=False)
result = comment_form.cleaned_data.get('body')
user = request.user.username
user_comment.author = request.user
user_comment.post = post
user_comment.save()
return JsonResponse({'result2': result, 'user': user})
比它完美地为我工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.