Is there any way to get csrftoken in View straightly?
I want to get the current csrftoken in view but will change sometimes so get it from Cookies is not a good idea.
Is there any way to do that?
Thanks!
To fetch a CRSF token, the app must send a request header called X-CSRF-Token with the value fetch in this call. The server generates a token, stores it in the user's session table, and sends the value in the X-CSRF-Token HTTP response header.
The CSRF token is like an alphanumeric code or random secret value that's peculiar to that particular site. Hence, no other site has the same code. In Django, the token is set by CsrfViewMiddleware in the settings.py file. A hidden form field with a csrfmiddlewaretoken field is present in all outgoing requests.
The CSRF protection is based on the following things: A CSRF cookie that is a random secret value, which other sites will not have access to. CsrfViewMiddleware sends this cookie with the response whenever django. middleware.
If you add @csrf_exempt to the top of your view, then you are basically telling the view that it doesn't need the token. This is a security exemption that you should take seriously. Follow this answer to receive notifications.
I believe you're looking for this:
django.middleware.csrf.get_token(request)
or
{% csrf_token %}
Reference: How can I embed django csrf token straight into HTML?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With