CSRF verification failed. Request aborted
Asked Answered
C

16

30

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

Cassiecassil answered 30/4, 2012 at 17:38 Comment(1)
Also make sure your browser accept cookies.Confederate
B
19

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})
Bowyer answered 30/4, 2012 at 17:44 Comment(0)
J
22

You may have missed adding the following to your form:

{% csrf_token %}
Jack answered 6/7, 2017 at 13:37 Comment(0)
B
19

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})
Bowyer answered 30/4, 2012 at 17:44 Comment(0)
B
17

add it to the setting file

CSRF_TRUSTED_ORIGINS = [
    'https://appname.herokuapp.com'
]
Bani answered 25/7, 2022 at 19:28 Comment(1)
clear, easy and simpleTenenbaum
R
10

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

    )

Rod answered 21/12, 2014 at 4:44 Comment(2)
Thanks for second part. I simply do not need that! :)Farquhar
Turning CSRF off is NOT a solution. Please don't do that. (part 2 of the answer)Triliteral
D
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..

Dalmatian answered 12/10, 2019 at 14:48 Comment(2)
It is from django.views.csrf.decorators import csrf_exempt instead of from django.views.decorators import csrf_exemptFlirtation
This is the solution that worked for me with Django 3.1.1 but you need to from django.views.decorators.csrf import csrf_exemptInterferometer
K
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.

Kenelm answered 10/3, 2014 at 2:54 Comment(0)
R
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');
}
Rhyner answered 6/3, 2016 at 23:28 Comment(0)
R
2

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

Reata answered 1/7, 2021 at 0:19 Comment(0)
R
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 ) {
    });
Rod answered 23/7, 2015 at 12:11 Comment(1)
You should wrote your ajax like that.Rod
U
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;
});
Upturn answered 29/7, 2015 at 14:35 Comment(0)
L
0

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

Lorou answered 20/3, 2020 at 10:58 Comment(2)
This almost8 years old question clearly describes I really have NO idea on where and how to use it. So how is this an answer?Coleslaw
@Coleslaw 1) sometime {% csrf_token %} not used in html-form then used othervise 2) we used {% csrf_token %} in template but they have some error is given that time you check that line in out of html-formLorou
E
0

USE decorator:

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def method_name():
    # body
Everyman answered 18/11, 2020 at 6:5 Comment(0)
B
0

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

Bruin answered 10/1, 2021 at 13:44 Comment(0)
E
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.

Ephraimite answered 1/3, 2023 at 20:18 Comment(0)
O
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>
Otto answered 19/9, 2023 at 15:36 Comment(0)
D
-1

CSRF(Cross-Site-Request-Forgery) helps in preventing attacks on a web application or a website. Each session in Django has it's own token and when a session expires the token is destroyed and you have to request for new tokens to access a session.In my case my session had ended and I was logged out of my session.I had to create a new superuser and log in again.

Dosh answered 19/2 at 21:37 Comment(1)
One thing I want to add on this error that you encountered is that the solution applies differently to other errors you encounter.Like my case I had all the requirements including the {% csrf_token %} and the rest of the files were in order but kept on getting the same error.Sometimes it's the minor details that matter.In this case I had to create a new superuser and refresh to get new tokens.I hope this clear and if it's not I'll be more than glad to help with where I can.Dosh

© 2022 - 2024 — McMap. All rights reserved.