Django CSRF:CSRF验证失败。单击“登录”按钮时请求中止

Django CSRF:CSRF验证失败。单击“登录”按钮时请求中止,django,django-csrf,Django,Django Csrf,我正在尝试建立一个简单的网站,在那里可以向MySQL数据库添加数据。我有一个带有两个文本输入(用户名、密码)的POST表单。我已经阅读了所有相关的答案,并试图解决它,但未能成功 index.html <form action="/login/" method="post">{% csrf_token %}<table border="0" cellspacing="15" width="345" align="center"> <tr> <td

我正在尝试建立一个简单的网站,在那里可以向MySQL数据库添加数据。我有一个带有两个文本输入(用户名、密码)的POST表单。我已经阅读了所有相关的答案,并试图解决它,但未能成功

index.html

<form action="/login/" method="post">{% csrf_token %}<table border="0" cellspacing="15" width="345" align="center">
<tr>
    <td width="100" >Username:</td>
    <td><input type="text" class="text-box" value="{{ username }}" placeholder="Username"/></td>                        
</tr>
<tr>
    <td class="align-left">Password:</td>
    <td><input type="password" class="text-box" value="" placeholder="Password"/></td>                        
</tr>                    
<tr>
    <td class="align-left"></td>
    forget-link"><a href="#" >Forget Your Passowrd?</a></td>                        
</tr>                    
url.py

urlpatterns = patterns('',      

    url(r'^login/', 'mysite.views.login', name='login'),
)
我在index.html中的form标记后应用了{%csrf_token%}

单击“登录”按钮时,出现以下错误:


CSRF验证失败。请求被中止。

我认为您需要将csrf应用到您的上下文中,您的视图会这样结束

from django.shortcuts import render_to_response
from django.core.context_processors import csrf

def login(request):

    logout(request) # not sure what this function is, I guess must be on some part of your code
    if request.method == "POST" :
        username = request.POST['username'] or ''
        password = request.POST['password'] or ''
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect('/main/')
    context = { 'username': username, }
    context.update(csrf(request))
    return render_to_response(request, 'index.html', context)

我认为你需要将csrf应用到你的环境中,你的观点会是这样的

from django.shortcuts import render_to_response
from django.core.context_processors import csrf

def login(request):

    logout(request) # not sure what this function is, I guess must be on some part of your code
    if request.method == "POST" :
        username = request.POST['username'] or ''
        password = request.POST['password'] or ''
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect('/main/')
    context = { 'username': username, }
    context.update(csrf(request))
    return render_to_response(request, 'index.html', context)

问题是,您正在模板中使用标记{%csrf_token%},但您之前没有在视图中生成该标记,因此模板对此一无所知

以下是您有两个选择:

第一个解决方案:

使用RequestContext,它始终使用 'django.core.context_processors.csrf'(无论您的 模板\上下文\处理器设置)。如果您使用的是常规视图 或contrib应用程序,由于这些应用程序使用 请求整个上下文

因此,您必须更改视图中的代码,如下所示:

def login(request):
    logout(request)
    username = password = ''
    if request.method :
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect('/main/')

    template = loader.get_template('index.html')
    context = RequestContext(request,{ 'username': username})
    return HttpResponse(template.render(context))
第二个解决方案:

手动导入并使用处理器生成CSRF令牌和 将其添加到模板上下文中。e、 g:

您的代码应该是(正如mcniac告诉您的):


问题是,您正在模板中使用标记{%csrf_token%},但您之前没有在视图中生成该标记,因此模板对此一无所知

以下是您有两个选择:

第一个解决方案:

使用RequestContext,它始终使用 'django.core.context_processors.csrf'(无论您的 模板\上下文\处理器设置)。如果您使用的是常规视图 或contrib应用程序,由于这些应用程序使用 请求整个上下文

因此,您必须更改视图中的代码,如下所示:

def login(request):
    logout(request)
    username = password = ''
    if request.method :
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect('/main/')

    template = loader.get_template('index.html')
    context = RequestContext(request,{ 'username': username})
    return HttpResponse(template.render(context))
第二个解决方案:

手动导入并使用处理器生成CSRF令牌和 将其添加到模板上下文中。e、 g:

您的代码应该是(正如mcniac告诉您的):



在哪个url上调用登录模板。它是/login/还是其他的?你添加了中间件吗?是的,我添加了中间件。Django的哪个版本?在哪个url上调用你的登录模板。它是/login/或任何其他的吗?你添加了中间件吗?是的,我添加了中间件。Django的哪个版本?很抱歉,我说了一半,现在你明白我的意思了。如果你使用的是Django formI,你就不需要它了。正如你所说,它已经应用了上下文,但仍然会得到相同的错误。在后端,我有like:/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py:55:UserWarning:A{%csrf_-token%}在模板中使用,但上下文没有提供值。这通常是由于不使用RequestContext造成的。warnings.warn(“模板中使用了{%csrf_token%},但上下文没有提供值。这通常是由于未使用RequestContext造成的。”)您如何提交表单?抱歉,有一半的评论,现在您明白我的意思了。如果您使用的是django formI,您不需要按照您所说的应用上下文,但仍然得到同样的错误。在后端,我有like:/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py:55:UserWarning:A{%csrf_-token%}在模板中使用,但上下文没有提供值。这通常是由于不使用RequestContext造成的。warnings.warn(“模板中使用了{%csrf_token%},但上下文未提供值。这通常是由于未使用RequestContext造成的。”)如何提交表单?模板中的和标记是否已正确关闭?您也可以尝试使用HttpResponse,而不仅仅是rendery,我已经关闭了所有标记。我还应用了HttpResponse。甚至思想错误也没有得到解决:(我已经用你的代码测试过了,它对我有效:(如果你使用的是Django 1.5+,只需在你的模板上做这个更改并尝试:){%csrf_token%}我正在使用django 1.4。我有一个用于登录的弹出框。它位于index.htmltry中,用于捕获请求上下文中的CSRF令牌,正如我编写的代码一样,您是否正确关闭了模板中的和标记?您也可以尝试使用HttpResponse,而不仅仅是rendery,我已经关闭了所有标记。我还应用了HttpResponse.Even思想错误没有得到解决:(我已经用你的代码进行了测试,它对我有效:(如果你使用Django 1.5+,只需在模板上做此更改并尝试:){%csrf_token%}我使用的是Django 1.4。我有一个用于登录的弹出框。它位于index.htmltry中,用于在请求上下文中捕获csrf令牌,正如我编写的代码一样