问题描述
我试图在帖子中添加评论,但它引发了这个错误,我使用 ajax 提交了我的评论,但问题似乎来自视图,但我无法弄清楚问题究竟是什么
@login_required
def add_comment_post(request):
comment_form = PostCommentForm(request.POST)
if comment_form.is_valid():
user_comment = comment_form.save(commit=False)
user_comment.author = request.user
user_comment.save()
result = comment_form.cleaned_data.get('content')
user = request.user.username
return JsonResponse({'result': result,'user': user})
我的评论模型
class PostCommentIDF(MPTTModel):
post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='pos_com')
parent = TreeForeignKey('self',null=True,blank=True,related_name='post_children')
author = models.ForeignKey(Account,on_delete=models.CASCADE)
content = models.TextField()
publish = models.DateTimeField(auto_Now_add=True)
status = models.BooleanField(default=True)
likes = models.ManyToManyField(Account,related_name='pos_com')
class MPTTMeta:
order_insertion_by = ['-publish']
def __str__(self):
return f'{self.author}---{self.content[:15]}'
我的评论表单
class PostCommentForm(forms.ModelForm):
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
class Meta:
model = PostCommentIDF
fields = {'post','content'}
widgets = {
'content': forms.Textarea(attrs={'class': 'rounded-0 form-control','rows': '1','placeholder': 'Comment','required': 'True'})
}
def save(self,**kwargs):
PostCommentIDF.objects.rebuild()
return super(PostCommentForm,self).save(*args,**kwargs)
模板中的评论表单
<form id="Postcommentform" class="Postcommentform" method="post" style="width: 100%;">
{% load mptt_tags %}
{% csrf_token %}
<select class="d-none" name="video" id="id_video">
<option value="{{ video.id }}" selected="{{ video.id }}"></option>
</select>
<div class="d-flex">
<label class="small font-weight-bold">{{ comments.parent.label }}</label>
{{ comment_form.parent }}
{{comments.content}}
<button value="Postcommentform" id="Postnewcomment" type="submit" style="color: white; border-radius: 0;" class="d-flex justify-content-end btn btn-primary">Post</button>
</div>
</form>
解决方法
当表单无效时,您的 if 语句下的代码将不会执行,因此您的函数将返回 None 而不是 HttpResponse。
您应该在 esle 语句中处理它,例如:
@login_required
def add_comment_post(request):
comment_form = PostCommentForm(request.POST)
if comment_form.is_valid():
user_comment = comment_form.save(commit=False)
user_comment.author = request.user
user_comment.save()
result = comment_form.cleaned_data.get('content')
user = request.user.username
return JsonResponse({'result': result,'user': user})
else:
return JsonResponse({'result': "form is not valid"})