禁用单个表单的csrf标记

时间:2015-10-27 22:34:17

标签: django csrf

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

2 个答案:

答案 0 :(得分:5)

您可以将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')

答案 1 :(得分:1)

您在评论中提到了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)
相关问题