Search code examples
djangodjango-csrf

Djangobook example: POST without {% csrf_token %} and passing context_instance=RequestContext(request). How?


I have implemented the following example from the djangobook, chapter 7, Tying Form objects into views (I'm using Django1.4):

# views.py

from django.shortcuts import render_to_response
from mysite.contact.forms import ContactForm

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})

# contact_form.html

<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">
        <table>
            {{ form.as_table }}
        </table>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

When I go to the url that I tied to this view and submit the form I get Forbidden(403) CSRF verification failed, Request aborted. I had to add {% csrf_token %} after <form action="" method="post">and pass context_instance=RequestContext(request) to render_to_response to get it working. Is there something I was doing wrong/some setting I oversaw because I don't understand how the author got this example working without the corrections I had to make. Btw I didn't change anything from the default settings configuration.


Solution

  • The Django book is written using Django 1.0 or 1.1. CSRF protection was changed in version 1.2 so that you need to explicitly insert the token.