19

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?

Mike M. Lin
  • 9,992
  • 12
  • 53
  • 62
  • 3
    Isn't it '{% csrf_token %}' - as a template tag, instead of outputting 'unicode(csrf_token)' ? – phoku Aug 02 '11 at 09:15
  • 1
    Gosh darn it. I can't think or read straight at 2 in the morning. You're absolutely right. Write it up as an answer and I'll accept it. Thanks much ;) – Mike M. Lin Aug 02 '11 at 09:18

2 Answers2

52

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

Pannu
  • 2,547
  • 2
  • 23
  • 29
11

I use the next in my templates to solve your problem:

<input type='hidden' name='csrfmiddlewaretoken' value='{{ csrf_token }}' />
ccsakuweb
  • 789
  • 5
  • 17