Django:CSRF令牌丢失或不正确

时间:2013-01-28 17:28:28

标签: python django csrf django-csrf

Django noob在这里!我已经尝试了基本上每个解决方案在线,我仍然有错误(一个Chrome)“CSRF令牌丢失或不正确”,而Opera和Firefox返回“CSRF cookie未设置”而是......?这是我的文件:

views.py

# views.py
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth import authenticate, login
from django.template import RequestContext
from django.core.context_processors import csrf

def dashboard(request):
    state = "log in"
    if request.user.is_authenticated():
        return render_to_response('memberbrd.html')
    elif request.method == "POST":
        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('/')
            else: 
                error = "inactive"
        else:
            error = "wrong username or password"
        render_to_response('visitorbrd.html', {'errors': error}, context_instance = RequestContext(request)) # I've also tried without context_instance, without passing errors...
    else:
        return render_to_response('visitorbrd.html')

urls.py

#urls.py
from django.conf.urls import patterns, include, url

from django.contrib import admin
admin.autodiscover()

from mission.views import *

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', dashboard),
)

visitorbrd.html

{% extends "base.html" %}
{% block content %}
    {% if state %}
        <p>{{ state }}</p>
    {% endif %}
    <form action="." method="POST">{% csrf_token %}
        <label for="username">User name:</label>
        <input type="text" name="username" value="" id="username">
        <label for="password">Password:</label>
        <input type="password" name="password" value="" id="password">
        <input type="submit" value="login" />
        <input type="hidden" name="next" value="{{ next|escape }}" />
    </form>
{% endblock %}

谢谢!

2 个答案:

答案 0 :(得分:3)

您没有将RequestContext用于负责实际显示表单的最终render_to_response

答案 1 :(得分:1)

之前的回答绝对正确。但是,不需要RequestContext来输出表单本身。这由Form类处理。问题是需要通过请求生成新的CSRF令牌,这是通过Django的中间件完成的。中间件只能访问上下文变量,因此通过该逻辑,它需要RequestContext来执行此操作。

另外,我更喜欢Django的“渲染”功能而不是“render_to_response”。有些时候这个功能太通用了,但是对于新用户来说,打字的节省很好,而且代码看起来更清晰。我从Django的网站上复制了这个例子(我下面也会包含一个永久链接)。

from django.shortcuts import render

def my_view(request):
    # View code here...
    return render(request, 'myapp/index.html', {"foo": "bar"},
        content_type="application/xhtml+xml")

Django Documentation: Shortcut Functions : render