Django FormView上的CSRF保护

时间:2015-03-03 18:58:06

标签: python django

例如,我在 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 装饰器吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

您应该在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。否则,您碰巧忘记装饰器的单个实例将立即带来安全风险。