13

Here's the relevant snippet of HTML in the template:

    <form action="/submit_text/" method="post">
    {% csrf_token %}
    {% include "backbone/form_errors.html" %}
    {{form.as_p}}
    <input type="submit" value="Submit" />
    </form>

Here is my settings.py MIDDLEWARE_CLASSES declaration:

MIDDLEWARE_CLASSES = ( 
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

The CSRF token simply doesn't show, causing a

Forbidden (403) CSRF verification failed. Request aborted.

Ben G
  • 26,091
  • 34
  • 103
  • 170

2 Answers2

22

You need to pass the RequestContext in your render_to_response for the context processors to actually be run.

 from django.template import RequestContext

 context = {}
 return render_to_response('my_template.html',
                           context,
                           context_instance=RequestContext(request))

the new render shortcut (django 1.3+) will do it for you:

 from django.shortcuts import render

 context = {}
 return render(request, 'my_template.html', context)
Sam Dolan
  • 31,966
  • 10
  • 88
  • 84
  • 1
    Very helpful! I had a custom template tag, so I had to specify `@register.simple_tag(takes_context = True)` and then `return render_to_string('template.html', {}, context_instance=context)`. – Sergey Orshanskiy Dec 16 '13 at 05:27
5

While there is a checked answer, I want to point out that writing context_instance.... gets really annoying. I find this useful...especially with forms

context.update(csrf(request))
CppLearner
  • 16,273
  • 32
  • 108
  • 163