Note that there are some explanatory texts on larger screens.

plurals
  1. POCSRF Protection in Django 1.4
    primarykey
    data
    text
    <p>I am trying to learn django by working through "The Django Book", and I'm having a problem with CSRF protection. I've found lots of suggestions here, but none seem to work for me. </p> <p>Using Chrome I get the message: <code>CSRF token missing or incorrect</code>.<br> Using Internet Explorer I get the message: <code>CSRF cookie not set</code>.</p> <p>If I comment out <code>'django.middleware.csrf.CsrfViewMiddleware'</code> in settings.py, everything seems to work (although nothing gets mailed to the phony address of course.) I've tried putting a <code>csrf_protect</code> decorator on my view, but it doesn't help. I've also tried commenting out the call to <code>send_mail</code>, and I still get a CSRF failure, so apparently it's the ContactForm which is causing the problem.</p> <p>(I'm using django 1.4.1.)</p> <p>What do I need to do?</p> <h3>views.py</h3> <pre><code>from django.shortcuts import render_to_response from django.http import HttpResponse, HttpResponseRedirect from contact.forms import ContactForm from django.template import RequestContext from django.core.mail import send_mail def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): cd = form.cleaned_data send_mail( cd['subject'], cd['message'], cd.get('email', 'noreply@example.com'), ['siteowner@example.com'], ) return HttpResponseRedirect('/contact/thanks/') else: form = ContactForm() return render_to_response('contact_form.html', {'form': form}, context_instance=RequestContext(request)) def thanks(request): return HttpResponse("Thanks for the feedback") </code></pre> <h3>forms.py</h3> <pre><code>from django import forms class ContactForm(forms.Form): subject = forms.CharField() email = forms.EmailField(required=False) message = forms.CharField() </code></pre> <h3>contact_form.html</h3> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Contact us&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Contact us&lt;/h1&gt; {% if form.errors %} &lt;p style="color: red;"&gt; Please correct the error{{ form.errors|pluralize }} below. &lt;/p&gt; {% endif %} &lt;form action="" method="post"&gt; &lt;table&gt; {{ form.as_table }} &lt;/table&gt; &lt;input type="submit" value="Submit"&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload