Categories: Web Dev Training

Disable CSRF Verification in Django Class-Based View

While working on a Django web app, I had to disable CSRF protection in a view. The goal was that our API was accepting data from another part of our website and we needed to skip the CSRF protection just for that one page.

There are two great answers on how to do this on StackOverflow:

  1. How to disable Django’s CSRF validation?
  2. How can I disable Django’s CSRF protection only in certain cases?

And nice documentation for Django Rest Framework on disabling CSRF for AJAX calls.

The answer is basically to use the csrf_exempt as a function that wraps the class-based view’s .as_view call and to do this in the urls.py routing file.

For example,

HelloView.as_view()

will become

csrf_exempt(HelloView.as_view())

Rudolf Olah is a software development expert with over 8 years of professional software developer experience. He has produced the video courses "Reactive Programming in Python with RxPy, PyQt5 and Tornado" and "Learning AngularJS Testing" for PacktPublishing. Rudolf offers web development training courses for individual developers and for web development teams. He writes about tech leadership, career coaching and project management.