How to Use csrf_token in Template in Django
In Django templates, use the
{% csrf_token %} tag inside your HTML <form> to add a hidden CSRF token input. This token helps protect your form from Cross-Site Request Forgery attacks by verifying requests on the server side.Syntax
Use the {% csrf_token %} tag inside your HTML form element in a Django template. It inserts a hidden input field with a unique token.
{% csrf_token %}: Django template tag that outputs the CSRF token input field.- Place it inside the
<form>tags before any input fields.
django
<form method="post"> {% csrf_token %} <!-- form fields here --> <button type="submit">Submit</button> </form>
Example
This example shows a simple Django template with a form that includes the {% csrf_token %} tag. When the form is submitted, Django checks the token to ensure the request is safe.
django
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSRF Token Example</title>
</head>
<body>
<h1>Submit Your Name</h1>
<form method="post" action="/submit-name/">
{% csrf_token %}
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<button type="submit">Send</button>
</form>
</body>
</html>Output
<form method="post" action="/submit-name/">
<input type="hidden" name="csrfmiddlewaretoken" value="random_token_value">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<button type="submit">Send</button>
</form>
Common Pitfalls
Common mistakes when using csrf_token include:
- Forgetting to add
{% csrf_token %}inside the form, causing CSRF verification to fail. - Using GET method forms which do not require CSRF tokens.
- Not enabling Django's CSRF middleware, which is required for token validation.
- Placing
{% csrf_token %}outside the<form>tags, so the token is not submitted.
django
<!-- Wrong: csrf_token outside form --> <form method="post"> <!-- form fields --> </form> {% csrf_token %} <!-- Right: csrf_token inside form --> <form method="post"> {% csrf_token %} <!-- form fields --> </form>
Quick Reference
| Usage | Description |
|---|---|
| {% csrf_token %} | Inserts a hidden CSRF token input inside a form. |
| Place inside | Must be inside the form tags to be submitted. |
| Works with POST forms | Required for POST, PUT, DELETE requests to prevent CSRF. |
| Requires CSRF middleware | Django's middleware must be enabled for validation. |
Key Takeaways
Always include {% csrf_token %} inside your HTML form tags in Django templates.
The CSRF token protects your site from malicious cross-site requests.
CSRF tokens are required for POST and other unsafe HTTP methods, not GET.
Ensure Django's CSRF middleware is enabled for token validation to work.
Placing {% csrf_token %} outside the form will cause CSRF validation errors.