[Django]-CSRF verification failed. Request aborted. on django

79πŸ‘

βœ…

You need to add the {% csrf_token %} template tag as a child of the form element in your Django template.

This way, the template will render a hidden element with the value set to the CSRF token. When the Django server receives the form request, Django will verify that the token matches the value that was rendered in the form. This is necessary to ensure that POST requests (i.e. data-altering requests) originate from an authentic client session.

For more info, check the Django documentation at:
https://docs.djangoproject.com/en/dev/ref/csrf/

Here is an overview of the Cross-Site Request Forgery attack:
https://www.owasp.org/index.php/CSRF

πŸ‘€fcurella

12πŸ‘

If you are using csrf_token template tag and the problem not solved, check CSRF_COOKIE_DOMAIN setting. You should set it to None on development environment.

πŸ‘€Mesut Tasci

9πŸ‘

I had the same problem. I solved this problem when i added the {% csrf_token %}. Finally my code is this:

 <form id='formulario2' method='post' action=''>
      <h3>Enter:</h3>
      {% csrf_token %}


     <input id="id_mesaje" name="mesaje" type="email" placeholder="E-mail"/>
    <input type='submit' name="boton2" value='Suscribete' style="display:inline-block;background-color: #80e174; "/>
 </form>

8πŸ‘

Just wanted give additional info on the topic. If it ever happens to you and you are sure that the token is injected in the form and the view functions are handling everything properly but the problem persists. Make sure that there is no javascript code disabling the input fields. Happened to me, after couple of hours of debugging, finally realized that.

<input type="hidden" name="csrfmiddlewaretoken" value="pHK2CZzBB323BM2Nq7DE2sxnQoBG1jPl" disabled="">
πŸ‘€amertkara

5πŸ‘

Add csrf_token to your POST form:

<form method="post" action=".">
    {% csrf_token %}
    ...
</form>

In Django 4.0, it is important to have CSRF_TRUSTED_ORIGINS set up as well.
See here

πŸ‘€DanielM

0πŸ‘

{% csrf_token %}

inside your form. This worked out for me. So why do we use the Cross-site requested forgery?

Well, the answer is pretty simple, it just added another security layer to your web page, whereby any malicious user cannot validate a request using a wrong token.

πŸ‘€Patcho

0πŸ‘

In your template after the form tag, you must and should put the CSRF token in a jing format on your template. For example {% csrf_token %}.

In any template that uses a POST form, use the csrf_token tag inside the element. If you don’t want to use the csrf_token then you can disable it from your settings file of the main app.

For your template just use

<form method="post" action=".">
    {% csrf_token %}
 //followed by rest of the tags
</form>
πŸ‘€Manukumar

Leave a comment