Search code examples
djangodjango-csrf

Can't Get CSRF Token to Appear on a Django Template/View


I'm trying to use a Django ListView sub-class to generate a page with a form on it. It's an old school manual HTML form, not a Django-generated one (though I do also have a Django-generated form elsewhere on the same page). Since Django bakes CSRF authentication in, I need to include the CSRF token in that form in order to make it work.

However, I'm not having much luck, even after looking at several related Stack Overflow posts (and fixing things accordingly).

Basically I've got a get method on a ListView subclass, and I've used the method decorator to decorate it with the CSRF decorator:

class FooView(ListView):
    @method_decorator(ensure_csrf_cookie)
    def get(self, request):
        # code for otherwise working view

In my template I have:

<form>
{% csrf_token %}

However, when I view the source of the page after it's been rendered, I just see:

<form>

(no CSRF token).

I'm not explicitly adding the CSRF token to the context because I'm using ListView, and as per https://docs.djangoproject.com/en/1.6/ref/contrib/csrf:

If you are using generic views or contrib apps, you are covered already

I'm sure I'm just missing something basic, but any help explaining what that might be would be greatly appreciated.


Solution

  • You need import this:

    from django.template import RequestContext
    

    and then use it like so:

    def example():
    
        # Some code
    
        return render_to_response('my_example.html', {
        'Example_var':my_var
        }, context_instance=RequestContext(request))
    

    This will force a {% csrf_token %} to appear.