csrf token fetch django

To fetch the CSRF token in Django, you can follow these steps:

  1. Import the csrf module from Django's middleware package.
  2. Use the get_token function from the csrf module to fetch the CSRF token.
  3. Pass the CSRF token to the template context or include it in the response.
  4. 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.