ValueError at /blog/1/comment/new/
The view blog.views.comment_new didn't return an HttpResponse object. It returned None instead.
Request Method: GET
Request URL: http://localhost:8000/blog/1/comment/new/
为什么请求方法得到?
HTML
<form action="" method="post">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type="submit" />
</form>
&#13;
视图
@login_required
def comment_new(request, post_pk):
post = get_object_or_404(Post, pk=post_pk)
if request.method == 'post':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.author = request.user
comment.save()
return redirect('blog:post_detail', post.pk)
else:
form = CommentForm()
return render(request, 'blog/comment_form.html', {
'form': form,
})`
感谢
答案 0 :(得分:1)
您只返回post方法的回复。你必须像这样重构你的代码。
def call_comment_form(request): #your function name
form = CommentForm()
if request.method == 'post':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.author = request.user
comment.save()
return redirect('blog:post_detail', post.pk)
else:
form = CommentForm(request.post) #this will return the errors in your form
return render(request, 'blog/comment_form.html', {
'form': form,
})`
当最初调用url时,它是GET方法,因此你必须先发送一个表单实例(空表单)。