Tub*_*ess 15 django csrf django-csrf
我是Django的新手,我仍然试图掌握它的功能.我用Django 1.4.2创建了一个非常简单的项目,它有一个简单形式的索引页面,你输入的东西和结果页面,你的输入在提交后显示(代码如下).
提交后,我收到错误403和以下消息:
模板中使用了{%csrf_token%},但上下文未提供值.这通常是由于不使用RequestContext引起的.warnings.warn(模板中使用了"A {%csrf_token%}",但上下文没有提供值.这通常是由于不使用RequestContext引起的.")
的index.html
<!DOCTYPE html>
<head>
<title>Index page</title>
</head>
<body>
<div id="header">Welcome to index page</div>
<div id="content">
<p>Enter your name</p>
<form action="/result/" method="post" accept-charset="utf-8">{% csrf_token %}
<input type="text" name="answer">
<input type="submit" value="Send!">
</form>
</div>
</body>
Run Code Online (Sandbox Code Playgroud)
result.html
<!DOCTYPE html>
<head>
<title>Result page</title>
</head>
<body>
<div id="header">Here is the result</div>
<div id="content">
<p>Your name is: {{ answer }}</p>
</div>
</body>
Run Code Online (Sandbox Code Playgroud)
views.py
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
def index(request):
return render_to_response('index.html')
def result(request):
p = request.POST['answer']
return render_to_response('result.html', {'answer': p}, context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)
我在互联网上查看了文档和各种示例,但我不明白我做错了什么.如果我在settings.py中禁用django.middleware.csrf.CsrfViewMiddleware,我会得到我想要的,但这不是我正在寻找的答案.
我感谢更有经验的Django忍者的帮助:-)
Ser*_*ney 30
你index.html没有被渲染RequestContext.试试这个:
def index(request):
return render_to_response('index.html', context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)
我还建议你使用更方便的快捷方式render:
from django.shortcuts import render
def index(request):
return render('index.html')
Run Code Online (Sandbox Code Playgroud)
来自docs:
render()与使用context_instance参数调用render_to_response()相同,后者强制使用RequestContext.
编辑:
感谢@nerdwaller提及,现在需要更新的版本:
render(request, 'index.html', {params});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
41533 次 |
| 最近记录: |