【发布时间】:2015-01-19 03:59:38
【问题描述】:
禁止 (403) CSRF 验证失败。 请求中止。失败原因:未设置 CSRF cookie。
我收到上述错误,并且有一些解决方案,但不适用于基于类的视图。 def get_context_data(self, **kwargs): 应该返回什么?在消息下方,它建议了 4 个解决方案,以下建议引起了我的注意。所以也许我应该以某种方式返回RequestContext?
视图函数使用 RequestContext 作为模板,而不是 Context。
我已经在使用{% csrf_token %},cookie 已启用,并且我已将其包含在中间件中。所以我想我可能返回了错误的东西,但这里的所有其他示例都使用函数视图。
我的模板 sn-p:
{% if not user.is_authenticated %}
<form id="login" method="post" action="login">{% csrf_token %}
<input type="text" name="username" value="" placeholder="Email">
<input type="password" name="password" value="" placeholder="Password">
<input type="submit" name="commit" value="Login">
</form>
{% elif user.is_authenticated %}
<p>Welcome, {{ user.get_displayname }}.</p>
{% endif %}
我的 urls.py:
from django.conf.urls import patterns, include, url
from mainapp.views import Index, LoginResponse
from django.contrib import admin
admin.autodiscover()
from mainapp import views
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^$', Index.as_view()),
url(r'^login$', LoginResponse.as_view()),
)
我的 LoginResponse 类视图:
class LoginResponse(TemplateView):
template_name = 'index.html'
def get_context_data(self, **kwargs):
context = super(LoginResponse, self).get_context_data(**kwargs)
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
return context
【问题讨论】:
-
那么 LoginResponse 是什么样的?
-
我在上面添加了类视图
-
那么这种观点毫无意义。您没有在任何地方定义
request,并且您忽略了authenticate的返回值-无论如何您都不应该在get_context_data内部进行身份验证。你确定这实际上是你的代码吗?如果你确实运行它,你肯定会得到一个 NameError。 -
实际上,您确定是视图首先呈现该模板吗?
-
@DanielRoseman,CSRF 中间件在访问视图之前拦截了请求,所以这就是他没有收到 NameError 的原因。
标签: python django python-2.7 django-1.7 django-csrf