Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 893
Mike M. Lin Avatar asked Aug 02 '11 09:08

Mike M. Lin


2 Answers

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

like image 167
Pannu Avatar answered Nov 06 '22 10:11

Pannu


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

<input type='hidden' name='csrfmiddlewaretoken' value='{{ csrf_token }}' />
like image 29
ccsakuweb Avatar answered Nov 06 '22 12:11

ccsakuweb