csrf token fetch django
To fetch the CSRF token in Django, you can follow these steps:
- Import the
csrf
module from Django'smiddleware
package. - Use the
get_token
function from thecsrf
module to fetch the CSRF token. - Pass the CSRF token to the template context or include it in the response.
- In the template, use the
{% csrf_token %}
template tag to include the CSRF token in the HTML form.
Here is an example:
from django.middleware import csrf
def my_view(request):
# Fetch the CSRF token
csrf_token = csrf.get_token(request)
# Pass the CSRF token to the template context or include it in the response
context = {
'csrf_token': csrf_token
}
return render(request, 'my_template.html', context)
In the template (my_template.html
), you can use the {% csrf_token %}
template tag to include the CSRF token in the HTML form:
<form method="post">
{% csrf_token %}
<!-- Other form fields -->
<button type="submit">Submit</button>
</form>
By including the CSRF token in the form, Django ensures that the form submission is secure and protected against cross-site request forgery attacks.