[Django]-CSRF verification failed. Request aborted

17πŸ‘

βœ…

Use the render shortcut which adds RequestContext automatically.

from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render
from steps_count.models import Top_List
from steps_count.forms import Top_List_Form


def index(request):

    if request.method == 'POST':
        #form = Top_List_Form(request.POST)
        return HttpResponse("Do something") # methods must return HttpResponse
    else:
        top_list = Top_List.objects.all().order_by('total_steps').reverse()
        #output = ''.join([(t.name+'\t'+str(t.total_steps)+'\n') for t in top_list])
        return render(request,'steps_count/index.html',{'top_list': top_list})
πŸ‘€Burhan Khalid

20πŸ‘

You may have missed adding the following to your form:

{% csrf_token %}
πŸ‘€unixia

12πŸ‘

add it to the setting file

CSRF_TRUSTED_ORIGINS = [
    'https://appname.herokuapp.com'
]
πŸ‘€Vaibhav Ugale

9πŸ‘

When you found this type of message , it means CSRF token missing or incorrect. So you have two choices.

  1. For POST forms, you need to ensure:

    • Your browser is accepting cookies.

    • In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.

  2. The other simple way is just commented one line (NOT RECOMMENDED)(β€˜django.middleware.csrf.CsrfViewMiddleware’) in MIDDLEWARE_CLASSES from setting tab.

    MIDDLEWARE_CLASSES = (
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        # 'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    

    )

6πŸ‘

One more nicest alternative way to fix this is to use '@csrf_exempt' annotation.

With Django 3.1.1 you could just use @csrf_exempt on your method.

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def index(request):

and you don’t need to specify {% csrf_token %} in your html.

happy learning..

3πŸ‘

A common mistake here is using render_to_response (this is commonly used in older tutorials), which doesn’t automatically include RequestContext. Render does automatically include it.

Learned this when creating a new app while following a tutorial and CSRF wasn’t working for pages in the new app.

πŸ‘€Pstrazzulla

2πŸ‘

In your HTML header, add

<meta name="csrf_token" content="{{ csrf_token }}">

Then in your JS/angular config:

app.config(function($httpProvider){
    $httpProvider.defaults.headers.post['X-CSRFToken'] = $('meta[name=csrf_token]').attr('content');
}

2πŸ‘

if you are using DRF you will need to add @api_view(['POST'])

πŸ‘€Fathy

0πŸ‘

function yourFunctionName(data_1,data_2){
        context = {}
        context['id'] = data_1
        context['Valid'] = data_2
        $.ajax({
            beforeSend:function(xhr, settings) {
                    function getCookie(name) {
                            var cookieValue = null;
                            if (document.cookie && document.cookie != '') {
                                var cookies = document.cookie.split(';');
                                for (var i = 0; i < cookies.length; i++) {
                                    var cookie = jQuery.trim(cookies[i]);
                                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                                        break;
                                    }
                                }
                            }
                            return cookieValue;
                        }
                        if (settings.url == "your-url")
                            xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
                    },

            url: "your-url",
            type: "POST",
            data: JSON.stringify(context),
            dataType: 'json',
            contentType: 'application/json'
        }).done(function( data ) {
    });

0πŸ‘

If you put {%csrf_token%} and still you have the same issue, please try to change your angular version. This worked for me. Initially I faced this issue while using angular 1.4.x version. After I degraded it into angular 1.2.8, my problem was fixed. Don’t forget to add angular-cookies.js and put this on your js file.
If you using post request.

app.run(function($http, $cookies) {
    console.log($cookies.csrftoken);
    $http.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken;
});

0πŸ‘

USE decorator:

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def method_name():
    # body
πŸ‘€Vishal Singh

0πŸ‘

Ensure that your browser is accepting cookies. I faced the same issues.

πŸ‘€Giri Kishore

0πŸ‘

<form action="/steps_count/" method="post">
 {% csrf_token %}
 Name: <input type="text" name="Name" /><br />
 Steps: <input type="text" name="Steps" /><br />
 <input type="submit" value="Add" />
</form>

Check your alignment it should be one space inside the form. That’s where almost everyone makes mistakes.

0πŸ‘

I got the same error below:

CSRF verification failed. Request aborted.

Because I did not set csrf_token tag in <form></form> with method="post" as shown below:

<form action="{% url 'account:login' %}" method="post">
  {% comment %} {% csrf_token %} {% endcomment %}
  ...
</form>

So, I set csrf_token tag in <form></form> with method="post" as shown below, then the error was solved:

<form action="{% url 'account:login' %}" method="post">
  {% csrf_token %}
  ...
</form>

In addition, whether or not you set csrf_token tag in <form></form> with method="get" as shown below, then there is no error. *only get and post request methods can be set to method for <form></form> but not head, put and so on according to the answer:

<form action="{% url 'account:login' %}" method="get">
  {% comment %} {% csrf_token %} {% endcomment %}
  ...
</form>
<form action="{% url 'account:login' %}" method="get">
  {% csrf_token %}
  ...
</form>

-1πŸ‘

1) {% csrf_token %} is not in template
β€” or β€”
2) {% csrf_token %} is outside of html-form

πŸ‘€vraj

Leave a comment