CSRF verification failed. Request aborted

Question:

I try to build a very simple website where one can add data into sqlite3 database. I have a POST form with two text input.

index.html:

{% if top_list %}
    <ul>
    <b><pre>Name    Total steps</pre></b>
    {% for t in top_list %}
        <pre>{{t.name}} {{t.total_steps}}</pre>
    {% endfor %}
    </ul>
    {% else %}
    <p>No data available.</p>
{% endif %}
<br>
<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>

forms.py:

from django import forms
from steps_count.models import Top_List

class Top_List_Form(forms.ModelForm):
    class Meta:
        model=Top_List

views.py:

# Create your views here.
from django.template import Context, loader
from django.http import HttpResponse
from steps_count.models import Top_List
from steps_count.forms import Top_List_Form
from django.template import RequestContext
from django.shortcuts import get_object_or_404, render_to_response

def index(request):

if request.method == 'POST':
    #form = Top_List_Form(request.POST)
    print "Do something"
else:
    top_list = Top_List.objects.all().order_by('total_steps').reverse()
    t = loader.get_template('steps_count/index.html')
    c = Context({'top_list': top_list,})
    #output = ''.join([(t.name+'t'+str(t.total_steps)+'n') for t in top_list])
    return HttpResponse(t.render(c))

However, when I click the “submit” button, I get the 403 error:

CSRF verification failed. Request aborted.

I have included {% csrf_token %} in index.html. However, if it is a RequestContext problem, I really have NO idea on where and how to use it. I want everything to happen on the same page (index.html).

Asked By: Bebe

||

Answers:

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})
Answered By: Burhan Khalid

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.

Answered By: Pstrazzulla

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',
    

    )

Answered By: Rajan Mandanka
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 ) {
    });
Answered By: Rajan Mandanka

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;
});

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');
}
Answered By: Olansile Ajibola

You may have missed adding the following to your form:

{% csrf_token %}
Answered By: unixia

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..

Answered By: Bandham Manikanta

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

Answered By: vraj

USE decorator:

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def method_name():
    # body
Answered By: Vishal Singh

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

Answered By: Giri Kishore

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

Answered By: Fathy

add it to the setting file

CSRF_TRUSTED_ORIGINS = [
    'https://appname.herokuapp.com'
]
Answered By: Vaibhav Ugale
<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.

Answered By: Anshuman Bisoyi