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

回眸只為那壹抹淺笑 提交于 2020-02-01 00:31:25

问题


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?


回答1:


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




回答2:


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

<input type='hidden' name='csrfmiddlewaretoken' value='{{ csrf_token }}' />


来源:https://stackoverflow.com/questions/6909694/djangos-csrf-token-is-outputting-the-token-value-only-without-the-hidden

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!