2017-07-15 148 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作爲字符串或將其定義爲變量 –

相關問題