Create Django Form with CSRF Token | Django Tutorials
June 8, 2021 2022-12-19 3:23Create Django Form with CSRF Token | Django Tutorials
Create Django Form with CSRF Token | Django Tutorials
Create Django Form with CSRF Token | Django Tutorials
Introduction to CSRF
Today we have to learn to create Django Form with CSRF Token, which is very important to know if you want to make a secure request. CSRF is related when unauthorized commands are submitted to the server. The server doesn’t know wheater this command request is coming from an authorized user or an unauthorized user. So the server cannot differentiate between them. That is why your data is lost due to the unauthorized submission of requests with your reference. So you have to secure your request from the attacker. To keep a safe request, Django provides some techniques, using that we can secure our request and CSRF attack.
Django CSRF verification failed
<form method=”POST” novalidate>
<div class=”input-group form-group”>
<input type=”text” name=”{{form.username.name}}” id=”input” class=”form-control” value=”” required=”required” pattern=”” title=””>
</div>
<div class=”input-group form-group”>
<input type=”password” name=”{{form.password.name}}” id=”input” class=”form-control” required=”required” title=””>
</div>
<div class=”form-group”>
<input type=”submit” value=”Login” class=”btn float-right login_btn”>
</div>
</form>
HTML Code | Django Form with CSRF Token
As you have checked errors when you submit a form using the POST method without adding a CSRF token. So, it explains here for you that you have to use the CSRF token in your Django form after the <form> tag. So, in this example, I will show you how you can add a CSRF token in your Django form to avoid unauthorized submission to the server. It is recommended to use in Form when using the POST method by Django. Let’s see another example
You did not do anything just after <form> tag just add {% csrf_token %} it will work to avodi CSRF attack.
<form method=”POST” >
{% csrf_token %}
{{ form.as_p }}Â <!– It will display all the django form feilds in paragrpah style–>
<button type=”submit” class=”save btn btn-default”>Save</button>
</form>
Conclusion
If you have any questions in your mind while reading out the tutorial, then must share them with us. We will provide you the best solution possible.
If you use Facebook, Twitter, Pinterest, LinkedIn, or other social media platforms, then share this Django tutorial, if you share, more students will take the chance to learn.
Recommended Django tutorials
Complete Tutorial on Django Form Validation | Django Tutorials