我正在编写一个新网站。现在我正在编写news_detail.html。此页面中有一个评论功能,供人们对新闻发表评论。
但我无法成功提交评论。
追溯说:
Exception Type: ValueError at /news-11
Exception Value: The view news.views.NewsDetailView didn't return an HttpResponse object. It returned None instead.
这是我的NewsComment模型:
class NewsComments(models.Model):
user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, verbose_name=u"用户")
news = models.ForeignKey(News, on_delete=models.CASCADE, verbose_name=u"新闻")
comments = models.CharField(max_length=200, verbose_name=u"评论")
parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.SET_NULL)
add_time = models.DateTimeField(auto_now_add=True, verbose_name='发时')
last_updated_time = models.DateTimeField(auto_now=True, verbose_name='更时')
is_delete = models.BooleanField(default=False, verbose_name='删否')
class Meta:
verbose_name = "新闻评论"
verbose_name_plural = verbose_name
ordering = ['-add_time']
def __str__(self):
return self.comments
这是我的新闻/ urls.py:
path('-<int:news_pk>', NewsDetailView.as_view(), name="news_detail"),
这是news / views.py:
class NewsDetailView(View):
def get(self, request, news_pk):
news = News.objects.get(id=int(news_pk))
title = news.title
author = news.author_name
add_time = news.add_time
content = news.content
category = news.category
tags = news.tag.annotate(news_count=Count('news'))
all_comments = NewsComments.objects.filter(news=news)
return render(request, 'news_detail.html',
{
'title': title,
'author': author,
'add_time': add_time,
'content': content,
'tags': tags,
'category': category,
'all_comments': all_comments
})
def post(self, request, news_pk):
comment_form = CommentForm(request.POST)
if comment_form.is_valid():
comments = comment_form.cleaned_data.get("comment")
comment = NewsComments(user=request.user,comments=comments,news=News.objects.get(id=news_pk))
comment.save()
comment_form = CommentForm
return render(request, "news_detail.html",
{
'comment_form': comment_form
})
这是CommentForm:
def words_validator(comment):
if len(comment) < 5:
raise ValidationError("您输入的评论字数太短,请重新输入至少5个字符")
class CommentForm(forms.Form):
comment = forms.CharField(widget=forms.Textarea(), validators=[words_validator])
这是我的news_detail.html:
<form method="post" action="">
<div class="form-group">
<label for="exampleFormControlTextarea1"><h5>评论 <i class="fa fa-comments"></i></h5></label>
<textarea id="js-pl-textarea" class="form-control" rows="4"
placeholder="我就想说..."></textarea>
<div class="text-center mt-3">
<button type="submit" id='js-pl-submit' class="btn btn-danger comment-submit-button">
发表评论
</button>
</div>
</div>
{% csrf_token %}
</form>
在我在管理员中添加一些注释后,我可以成功地在html中呈现注释。但是当我尝试提交表单并将注释保存在数据库中时,它总是失败。
答案 0 :(得分:1)
两个选项:
1)通过上下文发送所需的参数,对表单操作url
非常有用''' codes '''
def get(self, request, news_pk):
news = News.objects.get(id=int(news_pk))
''' codes '''
return render(request, 'news_detail.html',{
#codes
'title': title,
'news_pk': news_pk})
<强> HTML 强>
<form method="post" action="{% url 'news_detail' news_pk %}">{% csrf_token %}
<div class="form-group"></ div>
</form>
2)无需设置网址,因为模板news_detail.html
既是您的视图呈现的模板html,也是接收帖子请求的视图。
<form method="post" action="">{% csrf_token %} <!-- Make sure to keep action blank -->
<div class="form-group"></ div>
</form>
编辑:
考虑重新定义您的观点
注意更改,函数名称以小写字母开头
<强> views.py 强>
def newsDetailView(request,news_pk):
news = News.objects.get(id=news_pk)
title = news.title
author = news.author_name
add_time = news.add_time
content = news.content
category = news.category
tags = news.tag.annotate(news_count=Count('news'))
all_comments = NewsComments.objects.filter(news=news)
comment_form = CommentForm(request.POST or None)
if request.method == 'POST' and comment_form.is_valid():
comments = comment_form.cleaned_data.get("comment")
comment = NewsComments(user=request.user,comments=comments,news=news)
comment.save()
return render(request,"news_detail.html",{
'title': title,
'author': author,
'add_time': add_time,
'content': content,
'tags': tags,
'category': category,
'all_comments': all_comments
'comment_form': comment_form
})
<强> urls.py 强>
注意更改,将函数调用为低位字母,然后删除
.as_view()
path('-<int:news_pk>', newsDetailView, name="news_detail"),