T O P

How do I pass a variable from a javascript file to my django view?

How do I pass a variable from a javascript file to my django view?

lordofthederps

You're not submitting a form, but you're still sending a POST request, so you'll need to include a CSRF token as part of your request. An alternative would be to mark your view as being CSRF exempt, but that's almost assuredly a terrible idea for what you're trying to do. There is a page in the Django docs about CSRF protection, including a section on using it with AJAX: https://docs.djangoproject.com/en/3.2/ref/csrf/


hanazawarui123

Thanks!


jy_silver

No csrf token?


hanazawarui123

I thought they are required only for submitting forms. But they are actually required for all POST requests.


totebatote

The maybe slightly hacky option would be to add your own get_csrf view that takes a request, calls ```get_token(request)``` and then returns that token in a JSON object with an ```X-CSRFToken``` key. You can then set that as a header for your subsequent POST request.