【问题标题】:Why am i getting a csrf error in my POST form? (django/python) [duplicate]为什么我的 POST 表单中出现 csrf 错误? (django/python)[重复]
【发布时间】:2013-11-03 05:42:14
【问题描述】:

views.py

from django.shortcuts import render_to_response
from django.core.context_processors import csrf
def home(request):  
    c = {}
    c.update(csrf(request))
    if request.method == "POST":
        username = request.POST.get("username", '') 
        password = request.POST.get("password", '') 
        return render_to_response("login_home.html", {"username":username, "password":password})
    else:
        return render_to_response("login_home.html")

login_home.html

{% extends "base.html" %}
{% block page %}
    {{ name }}
    <form action = "/blog/home/" method = "POST">{% csrf_token %}
    <input type = "text" name = "username" placeholder = "username">
    <input type = "text" name = "password" placeholder = "password">
    <input type = "submit">
    </form>

    {{ username }}
    {{ password }}

{% endblock %}

urls.py

from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
    url(r'^home/$', 'blog.views.home'),
)

^^这是我的文件。问题是我提交表单后遇到的错误:

Forbidden (403)
CSRF verification failed. Request aborted.

我不确定我忘记或错过了什么。我猜它在视图函数中的某个地方。有人可以指出我缺少的一点吗?

感谢您的帮助。

【问题讨论】:

    标签: python django


    【解决方案1】:

    您需要使用RequestContext 或返回您使用c.update(csrf(request)) 创建的上下文:

    https://docs.djangoproject.com/en/dev/ref/contrib/csrf/

    1. 使用 RequestContext,它始终使用“django.core.context_processors.csrf”(无论您的 TEMPLATE_CONTEXT_PROCESSORS 设置如何)。如果您使用的是通用视图或贡献应用程序,那么您已经被覆盖了,因为这些应用程序自始至终都使用 RequestContext。

    2. 手动导入并使用处理器生成 CSRF 令牌并将其添加到模板上下文中。比如……

    return render_to_response("login_home.html",
        {"username":username, "password":password}
        context_instance=RequestContext(request))
    

    【讨论】:

    • 那我应该把我的代码改成什么?
    • 我已经给你看了;给你添加一个RequestContext render_to_response 方法
    猜你喜欢
    • 1970-01-01
    • 2017-07-19
    • 2012-12-30
    • 2013-07-13
    • 1970-01-01
    • 2014-02-06
    • 2013-06-11
    • 2019-08-11
    • 2021-07-24
    相关资源
    最近更新 更多