Search code examples
djangocsrf

Django CSRF Failure After Upgrade 1.9 > 1.11


I've just upgraded an app I'm developing from 1.9 to 1.11 and am getting constant errors on all form posts:

CSRF token missing or incorrect.

All CSRF tokens were working fine in 1.9. Here is the view:

def contact(request):
    subject = request.GET.get('subject', '')
    contact_form = forms.ContactForm(subject=subject)

    if request.POST:
        contact_form = forms.ContactForm(request.POST)

        if contact_form.is_valid():
            new_contact = contact_form.save()
            logic.send_contact_message(new_contact, request)
            messages.add_message(request, messages.SUCCESS, 'Your message has been sent.')
            return redirect(reverse('contact'))

    template = 'journal/contact.html'
    context = {
        'contact_form': contact_form,
        'contacts': core_models.Contacts.objects.filter(content_type=request.content_type,
                                                    object_id=request.site_type.pk)
    }

    return render(request, template, context)

Here is the template:

            <h4>{% trans "Contact" %}</h4>
            <form method="POST">
                {% include "elements/forms/errors.html" with form=contact_form %}
                {% csrf_token %}
                <label for="id_recipient">{% trans "Who would you like to contact?" %}</label>
                <select id="id_recipient" name="recipient">
                    {% for contact in contacts %}<option value="{{ contact.email }}">{{ contact.name }}, {{ contact.role }}</option>{% endfor %}
                </select>
                {{ contact_form.sender|foundation }}
                {{ contact_form.subject|foundation }}
                {{ contact_form.body|foundation }}
                {{ contact_form.are_you_a_robot|foundation }}
                <button type="submit" class="success button">{% trans "Send Message" %}</button>
            </form>

Solution

  • Django 1.10 introduced salted CSRF tokens that change every time the user logs in:

    Changed in Django 1.10:

    Added salting to the token and started changing it with each request to protect against BREACH attacks.

    You will have to log out and back in again to generate a new salted token before your forms will work.

    Melvyn suggests clearing your session store in a comment. That would work too, and is probably a better option if you have many users.

    You might also have to modify your middleware settings to reflect the new style introduced in Django 1.10. The old MIDDLEWARE_CLASSES setting is deprecated in favour of MIDDLEWARE. Make sure that 'django.middleware.csrf.CsrfViewMiddleware' is included in your MIDDLEWARE. If you have custom middleware (or if you're using libraries that use old-style middleware) it will have to be updated.