【发布时间】:2015-10-27 22:34:17
【问题描述】:
我有一个 html 表单,可以将帖子数据从另一个位置发送到 django web 应用程序。如何禁用该特定表单或请求的 csrf 令牌检查?
【问题讨论】:
我有一个 html 表单,可以将帖子数据从另一个位置发送到 django web 应用程序。如何禁用该特定表单或请求的 csrf 令牌检查?
【问题讨论】:
您可以将 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。如果您使用的是 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)
【讨论】: