Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
CSRF Token | Request Handling
Django: First Dive
course content

Course Content

Django: First Dive

Django: First Dive

1. Get Started
2. Write the First Page
3. Models
4. Working with Database
5. Templates
6. Request Handling

bookCSRF Token

Let's create the post_create.html file.

To create a post with specified parameters (title, text), we need to create a form for it.

Note

You can read about forms in the Ultimate HTML course.

html

index

css

index

js

index

copy

Now, we have a form, but Django has different security tools. One of these is a CSRF Token.

CSRF (Cross-Site Request Forgery) is an attack that tricks a user's browser into making unwanted or malicious requests on their behalf. To protect against this attack, Django generates a unique CSRF token for each user session. This token is included in forms or as a header in HTTP requests. When a form is submitted or an HTTP request is made, Django checks if the received token matches the one associated with the user's session, thus ensuring that the request originates from the expected source. It helps prevent unauthorized actions and adds an extra layer of security to web applications.

We need to put the CSRF Token to the response using the DTL (Django Template Language).
To do this, it is necessary to write {% csrf_token %} inside the form in the template:

Note

The CSRF Token will be passed through the form in any case. Therefore, its position is not important. The main thing is that it is inside the form tag - otherwise, it will not be passed.

Django automatically uses the provided token passed with the POST request from the same page. This allows us to quickly develop and avoid logic related to security against CSRF attacks.

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 6. Chapter 2
We're sorry to hear that something went wrong. What happened?
some-alt