1

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

视图.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')

网址.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),
)

访客brd.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 %}

谢谢 !

4

2 回答 2

3

您没有使用负责实际显示表单RequestContext的最终结果。render_to_response

于 2013-01-28T17:39:21.823 回答
1

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

附带说明一下,我更喜欢 Django 的“render”函数而不是“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 文档:快捷功能:渲染

于 2013-01-28T17:56:22.177 回答