【问题标题】:Django CSRF error on form submission表单提交时出现 Django CSRF 错误
【发布时间】:2013-07-13 20:42:21
【问题描述】:

我正在编写一个 Django 应用程序。这是我的代码:

edit.module.html(模板;删除额外的 html 标记):

<h1>Enter the HTML below</h1>
<form action="./update/" method="post">
    {% csrf_token %}
    <textarea cols='55' rows='15'></textarea>
    <input type='submit' value='Submit' />
</form>

urls.py

url(r'^myapp/update/$', 'myproj.myapp.views.update_module'),

view.py

from django.http import HttpResponse
from django.shortcuts import render_to_response, get_object_or_404
from django.core.context_processors import csrf
from django.template import RequestContext

#Select the module you want to edit
def edit_modules(request):
    lpconf = {"module_to_edit" : "top"}
    return render_to_response('admin/edit.module.html', lpconf, context_instance=RequestContext(request))

def update_module(request):
    return render_to_response('admin/updated.html', context_instance=RequestContext(request))

当我提交表单时,我收到 CSRF 错误:“CSRF 验证失败。请求中止。”

我遵循 Django 文档 (https://docs.djangoproject.com/en/dev/ref/contrib/csrf/) 并尝试解决问题,但我无法解决。我在这里做错了什么?

谢谢。

更新:更新了 view.py 函数 edit_modules 和 update_modules。 edit_modules 是渲染表单的工具,update_modules 是处理表单的工具。现在,我没有收到 CSRF 错误。我现在收到错误:Empty module name

更新:我能够修复它。我使用一个视图来呈现表单,而另一个视图来处理它。我必须为呈现表单的第一个视图添加上下文。

【问题讨论】:

    标签: python django


    【解决方案1】:

    您的update_module 视图中需要RequestContext,而不是普通的旧HttpResponse。如果您使用方便的render shortcut,它将自动添加。在 Django 教程中有一个很好的快速介绍; A shortcut: render().

    【讨论】:

    • 我需要传递一个实际的模板 html 文件来完成这项工作吗?我不能只传递一些文本消息而不必使用实际的 HTML 文件吗?
    • 你可能应该定义一个合适的 HTML 模板,在你的模板目录中创建一个不会花时间!
    • 是的,我刚刚做了,在视图中我将代码更新为“return render(request, 'updated.html')”。仍然存在相同的 CSRF 错误。我还导入了“从 django.shortcuts 导入渲染”
    • @Leon form handling 的 Django 教程可能会派上用场。您应该在 update_module 视图中检查表单是否已发布,如果没有,则呈现表单。
    • @Leon 看起来好像您必须使用单独的视图呈现表单本身?我通常使用相同的视图处理和呈现 POST 表单,并在成功时使用HttpResponseRedirect。也许这就是麻烦?
    【解决方案2】:

    您可以在 settings.py 中启用请求上下文进程

    TEMPLATE_CONTEXT_PROCESSORS = (...
        "django.core.context_processors.request")
    

    所以你不必这样做:

    return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request)
    

    相反,简单地说: return render_to_response('my_template.html', my_data_dictionary)

    另外,请确保在您的 settings.py 中的 MIDDLEWARE_CLASSES 中启用了“django.middleware.csrf.CsrfViewMiddleware”

    【讨论】:

      猜你喜欢
      • 2012-05-03
      • 2021-07-09
      • 2020-05-30
      • 2014-11-11
      • 2015-10-21
      • 2011-07-28
      • 2014-02-25
      • 2018-11-24
      • 2017-08-24
      相关资源
      最近更新 更多