【问题标题】:Disable csrf token for a single form为单个表单禁用 csrf 令牌
【发布时间】:2015-10-27 22:34:17
【问题描述】:

我有一个 html 表单,可以将帖子数据从另一个位置发送到 django web 应用程序。如何禁用该特定表单或请求的 csrf 令牌检查?

【问题讨论】:

    标签: django csrf


    【解决方案1】:

    您可以将 csrf_exempt 装饰器添加到您的视图中。

    示例

    from django.views.decorators.csrf import csrf_exempt
    from django.http import HttpResponse
    
    @csrf_exempt
    def my_view(request):
        return HttpResponse('Hello world')
    

    【讨论】:

    • 不是为了一个视图,只是一个表单。是一个向导表单(crispyform),我只想禁用它们中的第一个
    • 您应该更新您的问题并包含代码 sn-ps。
    【解决方案2】:

    您在评论中提到了 Crispyform。如果您使用的是 FormHelper 函数,那么解决方案是更改为设置 disable_csrf 属性。

    class ExampleForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(ExampleForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.disable_csrf = True
    

    查看这里了解更多信息:http://django-crispy-forms.readthedocs.org/en/latest/form_helper.html

    如果这给您带来任何麻烦,请查看他们的 test.py 文件:http://pydoc.net/Python/django-crispy-forms/1.3.0/crispy_forms.tests.tests/

    具体来说:

    def test_disable_csrf(self):
        form = TestForm()
        helper = FormHelper()
        helper.disable_csrf = True
        html = render_crispy_form(form, helper, {'csrf_token': _get_new_csrf_key()})
        self.assertFalse('csrf' in html)
    

    【讨论】:

      猜你喜欢
      • 2013-02-22
      • 2012-12-15
      • 2013-12-02
      • 2020-06-16
      • 2019-07-01
      • 2016-12-16
      • 2011-12-11
      • 1970-01-01
      • 2018-09-22
      相关资源
      最近更新 更多