2012-06-06 73 views
1

我收到錯誤,「CSRF令牌丟失或不正確」,但我相信我已經在模板中包含了正確的標記。下面是視圖和模板已經呈現出這樣的錯誤:如何解決CSRF驗證錯誤?

def contact(request): 
    if request.method == 'POST': 
     form = ContactForm(request.POST) 
     if form.is_valid(): 
      cd = form.cleaned_data 
      return HttpResponseRedirect('/contact/thanks/') 
    else: 
     form = ContactForm() 
    return render_to_response('reserve/templates/contact_form.html',{'form': form}) 

模板:中the instructions

<html> 
<head> 
    <title>Contact us</title> 
</head> 
<body> 
    <h1>Contact us</h1> 

    {% if form.errors %} 
     <p style="color: red;"> 
      Please correct the error{{ form.errors|pluralize }} below. 
     </p> 
    {% endif %} 

    <form action="" method="post"> 
    {% csrf_token %} 
     <table> 
      {{ form.as_p }} 
     </table> 
     <input type="submit" value="Submit"> 
    </form> 
</body> 
</html> 
+0

如果您查看模板HTML源代碼你看到的CSRF令牌字段設置? – Mikael

+0

還要確保您已將中間件添加到settings.py或正在使用@csrf_protect裝飾器。 – Mikael

+0

檢查如何在您的應用中使用它:https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#how-to-use-it – Mikael

回答

2

通告第3項。快速完成此操作的方法是用render(request, 'reserve/templates/contact_form.html',{'form': form})替換您的render_to_response呼叫(通過from django.shortcuts import render導入)。

0

你應該在上下文實例傳遞給您的選擇render_to_response

from django.template import RequestContext 

return render_to_response('reserve/templates/contact_form.html', context_instance=RequestContext(request,{'form': form}))