Django 的 {{ csrf_token }} 仅输出令牌值,没有隐藏的输入标记
当我使用 {{ csrf_token }}
时,为什么隐藏输入字段的标记不显示?
这是我的模板中的一个片段:
<form action="." method="post">
{{ csrf_token }}
我期待类似这样的内容要生成的:
<form action="." method="post">
<input type="hidden" name="csrfmiddlewaretoken" value="0c90dab91e22382cbaa5ef375f709167">
但是,这是生成的 HTML:
<form action="." method="post">
0c90dab91e22382cbaa5ef375f709167
我已经这样做了很多次,并且在我的其他项目中运行良好,但我不知道这次我错过了什么。
我的views.py 文件如下所示:
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))
如您所见,我正在使用RequestContext。我的中间件类在 settings.py 文件中定义如下:
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',
)
所以我使用 django.middleware.csrf.CsrfViewMiddleware。另外,我使用的是 Django 1.3.0。有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须将其用作标签
{% csrf_token %}
而不是视图传递的变量{{csrf_token}}
You have to use it as tag
{% csrf_token %}
not as a variable passed by your view{{csrf_token}}
我使用模板中的下一个来解决您的问题:
I use the next in my templates to solve your problem: