Skip to content
Advertisement

how to pass csrf_token to javascript file in django?

Here is my javascript code that works fine. but I like to keep javascript files seperate and not use as inline script tags

JavaScript

I want to include this in my custom.js file that I have included in my base.html. which is

JavaScript

I am not able to reference csrf_token that is available in the current template in Django to the static js file. how can I get this to work?

Advertisement

Answer

If you want to reference template tags then you need that file to be templated (rendered) by Django. And I wouldn’t recommend rendering all your static files via django…

You can either put the csrf_token in a global variable that you then access from your script. Something like this in your base.html:

JavaScript

Or you can pull the csrftoken from the cookies in your javascript file. See this question for a solution for that. The cookie is called csrftoken. You can view it by opening up your dev tools and looking at the cookies for your domain.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement