2017-07-15 144 views
-1
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/ 

为什么请求方法得到?Django没有返回HttpResponse对象错误?

HTML

<form action="" method="post"> 
 
    {% csrf_token %} 
 
    <table> 
 
    {{ form.as_table }} 
 
    </table> 
 
    <input type="submit" /> 
 
</form>

VIEWS

@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

为什么你没有在html表单中指定任何操作参数 –

+0

我现在不需要参数。 –

+1

你应该指定一个动作url,否则你将如何确保没有额外的混乱被发送到服务器 –

回答

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方法,所以你必须先发送形式的实例(空单)。

+0

这完全不回答OP的问题。 OP询问为什么他的请求方法是在他把html发布后发布的。您可能需要重构此答案,以便在使用表单时完成 –

+0

,如果您要求为表单创建新条目,它最初将成为GET方法。但是当你提交表单时,它应该是POST方法。我们不应该在GET中提交表单,以确保当我们将响应发送回服务器时,表单中填写的数据不会暴露。 –

+0

耶正确无论你在说什么关于曝光和其他。但你仍然没有回答我问的问题。在你的答案'{contextdata:data}'中也有一个语法错误,你可能想使用contextdata作为字符串或将其定义为变量 –

相关问题