Django's {{ csrf_token }} is outputting the token value only, without the hidden input markup

Mike M. Lin picture Mike M. Lin · Aug 2, 2011 · Viewed 16.9k times · Source

Why isn't the markup for the hidden input field showing up when i use {{ csrf_token }}?

Here's a snippet from my template:

<form action="." method="post">
{{ csrf_token }}

I'm expecting something like this to be generated:

<form action="." method="post">
<input type="hidden" name="csrfmiddlewaretoken" value="0c90dab91e22382cbaa5ef375f709167">

But instead, this is the HTML that's generated:

<form action="." method="post">
0c90dab91e22382cbaa5ef375f709167

I've done this many times and it's working fine in my other projects, but I don't know what I missed this time.

My views.py file looks like this:

from django.shortcuts import render_to_response
from django.template import RequestContext

def home(request):
    return render_to_response('home.html',
                              context_instance=RequestContext(request))

As you can see, I'm using RequestContext. My middleware classes are defined like this in the settings.py file:

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',
)

So I am using django.middleware.csrf.CsrfViewMiddleware. Also, I'm on Django 1.3.0. Any ideas out there?

Answer

Pannu picture Pannu · Aug 2, 2011

You have to use it as tag {% csrf_token %} not as a variable passed by your view {{csrf_token}}