Cross-site request forgery (CSRF) tricks a user into submitting an unintended action to a site where they are already signed in. A malicious site can imitate an ordinary form while quietly changing something important on the real site, such as the user’s password. section 7.1.2
Django blocks this request-forgery pattern with the {% csrf_token %} template tag and CsrfViewMiddleware. The middleware creates a session cookie containing a random value. The tag places a variation of that value in the form as a hidden field. When the form is submitted, Django checks that the token exists and matches the session value; otherwise, it rejects the POST. section 7.1.2
A forged password form
Imagine a malicious page styled like a harmless comment form. Its hidden fields actually request a password change on the real site. The user clicks Submit, and the browser sends the request. A legitimate Django form includes {% csrf_token %}; the attacker’s form cannot know the required token value, so Django rejects the forged POST. section 7.1.2
A protected Django form follows this request flow:
- Render the form with {% csrf_token %}, adding the hidden protection field. section 7.1.2
- Submit the form as a POST, sending the hidden token alongside the user’s data. section 7.1.2 section 7.6
- Let CsrfViewMiddleware compare the submitted token with the value stored in the session cookie. section 7.1.2
- Continue only when the values match; reject the POST when the token is missing or incorrect. section 7.1.2




