[英]CSRF protection on Django FormView
例如,我在views.py中使用它:
@csrf_protect
def contacts(request):
pass
现在我想使用FormView :
class ContactFormView(FormView):
template_name = 'contacts.html'
form_class = ContactForm
success_url = '/'
def form_valid(self, form):
# This method is called when valid form data has been POSTed.
# It should return an HttpResponse.
form.send_email()
return super(ContactFormView, self).form_valid(form)
所以,我需要在哪里使用@csrf_protect装饰器?
谢谢!
您应该在dispatch
方法上使用method_decorator
:
from django.utils.decorators import method_decorator
class ContactFormView(FormView):
...
@method_decorator(csrf_protect)
def dispatch(self, *args, **kwargs):
return super(ContactFormView, self).dispatch(*args, **kwargs)
但是,强烈建议改用CsrfViewMiddleware
。 否则,您偶然忘记装饰器的单个实例将立即带来安全风险。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.