我是 Django 的新手,我仍在尝试掌握它的功能。我创建了非常简单的项目姜戈 1.4.2它有简单形式的索引页面,您可以在其中输入内容,还有结果页面,您的输入在提交后显示(代码如下)。
提交后,我收到错误 403 和以下消息:
模板中使用了 {% csrf_token %},但上下文没有
提供价值。这通常是由于没有使用引起的
请求上下文。 warnings.warn("A {% csrf_token %} 被用于
模板,但上下文没有提供该值。这通常是
由于未使用 RequestContext 造成的。”)
索引.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>
结果.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>
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))
我查看了互联网上的文档和各种示例,但我不明白我做错了什么。如果我禁用django.middleware.csrf.CsrfViewMiddleware in 设置.py,我得到了我想要的,但这不是我正在寻找的答案。
我感谢更有经验的 Django 忍者的帮助:-)
Your index.html
渲染时没有RequestContext
。尝试这个:
def index(request):
return render_to_response('index.html', context_instance=RequestContext(request))
我还建议您使用更方便的快捷方式render https://docs.djangoproject.com/en/dev/topics/http/shortcuts/#render:
from django.shortcuts import render
def index(request):
return render('index.html')
来自文档:
render() 与调用 render_to_response() 相同
context_instance 参数强制使用 RequestContext。
EDIT:
Thanks @nerdwaller https://stackoverflow.com/u/1584762/值得一提的是,新版本现在需要:
render(request, 'index.html', {params});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)