Conteúdo do Curso
Django: First Dive
Django: First Dive
CSRF 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.
index
index
index
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.
Obrigado pelo seu feedback!