【问题标题】:What should return when using CSRF tokens with class-based views?将 CSRF 令牌与基于类的视图一起使用时应该返回什么?
【发布时间】: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


【解决方案1】:

对于 CSRF 验证,基于函数的视图和基于类的视图没有区别。此验证在中间件级别完成。

所以请显示您的模板和 urls.py。

【讨论】:

  • 在原帖中添加了模板和urls.py
  • 嗯,看起来不错。确定您指向有效视图吗?然后你从MIDDLEWARE_CLASSES 中注释掉django.middleware.csrf.CsrfViewMiddleware 会发生什么?并且,以防万一,展示你的观点。
  • 没有CsrfViewMiddleware可以试试这个视图吗?
  • 我删除了它,现在登录后,我进入一个位于/login 的纯白页面,但我回到主页,django 模板语言认为我不是登录。我可能需要搜索我的浏览器 cookie 来确认
  • 你有问题urls.py。您应该得到一个标准的 django 错误页面,而不是空白的白页(您的视图不正确并引发 NameError)。向我们展示一个完整的 urls.py。
猜你喜欢
  • 1970-01-01
  • 2014-07-23
  • 2013-05-01
  • 2016-05-13
  • 2022-12-16
  • 2019-02-11
  • 1970-01-01
  • 2012-07-22
  • 2014-03-19
相关资源
最近更新 更多