【问题标题】:Django - {% csrf_token %} was used in a template, but the context did not provide the valueDjango - {% csrf_token %} 在模板中使用,但上下文没有提供值
【发布时间】:2012-10-14 10:26:11
【问题描述】:

我是 Django 新手,我仍在努力掌握它的功能。我使用 Django 1.4.2 创建了非常简单的项目,该项目具有简单表单的索引页面,您可以在其中输入内容,并在提交后显示您的输入的结果页面(代码如下)。

提交后,我收到错误 403 和以下消息:

在模板中使用了 {% csrf_token %},但上下文没有 提供价值。这通常是由于没有使用 请求上下文。 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>

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>

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))

我查看了 Internet 上的文档和各种示例,但我不明白我做错了什么。如果我在 settings.py 中禁用 django.middleware.csrf.CsrfViewMiddleware,我得到的正是我想要的,但这不是我想要的答案。

感谢更有经验的 Django 忍者的帮助 :-)

【问题讨论】:

  • 你在尝试使用 django runserver 吗?
  • 是的,我正在使用“manage.py runserver”进行测试。有什么限制吗?

标签: django csrf django-csrf


【解决方案1】:

我在使用 Django 2.1 时遇到了这个错误,原来它是由另一个 ajax 请求调用的模板中的 ajax 请求引起的。因此,解决方案是将“request=request”添加到我的渲染函数中:

args = {'someargs': somevalues}
html = render_to_string(
        'my_template.html', context=args, request=request)
return HttpResponse(html)

【讨论】:

    【解决方案2】:

    您的index.html 在没有RequestContext 的情况下呈现。试试这个:

    def index(request):
        return render_to_response('index.html', context_instance=RequestContext(request))
    

    我也建议你使用更方便的快捷方式render

    from django.shortcuts import render
    
    def index(request):
        return render('index.html')
    

    来自文档:

    render() 与调用 render_to_response() 相同 强制使用 RequestContext 的 context_instance 参数。

    编辑

    感谢@nerdwaller提及,现在需要更新版本:

    render(request, 'index.html', {params});
    

    【讨论】:

    • 天哪,我真傻。这一直是解决方案。我以为我只需要在实际发送 POST 数据的视图中定义 RequestContext 。谢谢@goliney!
    • 感谢专业提示!我的问题解决了,你的回答被接受了:-)
    • 最新版本的 django 要求:render(request, 'index.html', {params}); 供任何人查看。 See here
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    • 1970-01-01
    • 2017-01-27
    • 1970-01-01
    • 2011-12-27
    相关资源
    最近更新 更多