【问题标题】:Django RedirectView "CSRF token missing or incorrect."Django RedirectView“CSRF 令牌丢失或不正确。”
【发布时间】:2016-05-12 19:25:58
【问题描述】:

我遇到了 CSRF 验证问题,即使我正在使用 csrf_exempt 装饰器(通过辅助 mixin)。

这是我的代码:

class CSRFExemptMixin(object):
    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        return super(CSRFExemptMixin, self).dispatch(request, *args, **kwargs)

class IndexRedirectView(RedirectView, CSRFExemptMixin):
    permanent = False

    def get_redirect_url(self, *args, **kwargs):
        if self.request.user.visit_count >= 5:
            return reverse('gift-shop')
        if len(BaseGiftableInstance.objects.filter(giving_user=self.request.user)) > 0:
            # has won something
            return reverse('gift-shop')
        return reverse('spinner')

这是一个 Facebook 画布应用。

【问题讨论】:

  • 继承顺序很重要,我试试class IndexRedirectView(CSRFExemptMixin, RedirectView)
  • 谢谢。现在不会出现 CSRF 验证问题。但现在我得到一个空白屏幕。重定向不起作用。
  • 嗯。我想我找到了问题所在。它与从“https://”URL 到“http://”URL 的重定向有关。
  • 是的。现在我需要找到一种方法来强制 Django 使用 https URL。问题是我使用的是 Cloud9。在那里,我使用通常的 ./manage.py runserver 而不是 runsslserver,它使反向函数返回“http://”URL。但 Cloud9 实际上是通过 HTTPS 提供页面的。
  • 那是一个不同的问题,事实上,我恐怕无法帮助你......无论如何,如果我的提示有效,我会将它作为答案发布,以便你可以接受。我建议你用这个新问题创建一个新帖子;)

标签: python django python-2.7 redirect django-1.6


【解决方案1】:

由于继承顺序很重要,您应该替换

class IndexRedirectView(RedirectView, CSRFExemptMixin)

class IndexRedirectView(CSRFExemptMixin, RedirectView)

第一种情况,IndexRedirectViewdispatch()方法调用了RedirectView的方法,它没有csrf_exempt装饰器,导致CSRF验证失败。

【讨论】:

    猜你喜欢
    • 2021-07-14
    • 2021-11-13
    • 2012-04-20
    • 2012-09-25
    • 1970-01-01
    • 1970-01-01
    • 2016-06-10
    • 2017-09-14
    • 2019-12-04
    相关资源
    最近更新 更多