Search code examples
djangocsrfdjango-csrf

Django in an API like + reactjs. How to generate a csrf token


I did something a bit silly while developing my project:

I'm using django only for the admin and the views are used as urls for my front (reactjs) for get actions. I've nothing to protect about the data itself.

But the problem is that at some point I've got assets to download and this is the only time when I've to do a POST request to my django.

And here is the problem. Django is waiting for a csrf token and I didn't succeed on ignoring that (I'm using base-class views).

The really silly thing is that it was working until now as I was working with the django admin (which means django template -> csrf token generation). So for a standard user he won't have it...

Do you have an idea how I could proceed? Should I pass by a fake django view to be sure that the user got it? (seems to be an ugly solution).

Many thanks!


Solution

  • decorate dispatch method on CBV, it should resolve your post problem

    def MyView(View)
       @method_decorator(csrf_exempt)
       def dispatch(self, request, *args, **kwargs):
           return super(MyView, self).dispatch(request, *args, **kwargs)