禁止(403)CSRF验证失败。 请求中止。失败的原因:未设置CSRF cookie。
我得到了上述错误,并且有一些解决方案,但不适用于基于类的视图。 def get_context_data(self, **kwargs):
应该返回什么?在消息下方,它提出了4种解决方案,以下建议引起了我的注意。所以也许我应该以某种方式返回RequestContext
?
view函数使用RequestContext代替Context。
我已经在使用{% csrf_token %}
,已启用Cookie,我将其包含在中间件中。所以我认为我可能会返回错误的东西,但这里的所有其他示例都使用函数视图。
我的模板代码段:
{% 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
答案 0 :(得分:0)
对于CSRF验证,基于功能的视图和基于类的视图之间没有区别。此验证在中间件级别完成。
请显示您的模板和urls.py。