简体   繁体   English

Django FormView上的CSRF保护

[英]CSRF protection on Django FormView

For example, I use this in views.py : 例如,我在views.py中使用它:

@csrf_protect
def contacts(request):
    pass

Now I want to use FormView : 现在我想使用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)

So, where I need to use @csrf_protect decorator? 所以,我需要在哪里使用@csrf_protect装饰器?

Thanks! 谢谢!

You should use a method_decorator on the dispatch method: 您应该在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)

However, it's highly recommended to use the CsrfViewMiddleware instead. 但是,强烈建议改用CsrfViewMiddleware Otherwise, a single instance where you happen to forget the decorator will immediately impose a security risk. 否则,您偶然忘记装饰器的单个实例将立即带来安全风险。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM