简体   繁体   中英

CSRF protection on Django FormView

For example, I use this in views.py :

@csrf_protect
def contacts(request):
    pass

Now I want to use 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?

Thanks!

You should use a method_decorator on the dispatch method:

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. Otherwise, a single instance where you happen to forget the decorator will immediately impose a security risk.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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