CSRF verification failed. Request aborted CSRF verification failed. Request aborted python python

CSRF verification failed. Request aborted


Use the render shortcut which adds RequestContext automatically.

from django.http import HttpResponsefrom django.shortcuts import get_object_or_404, renderfrom steps_count.models import Top_Listfrom steps_count.forms import Top_List_Formdef 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})


You may have missed adding the following to your form:

{% csrf_token %}


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

    )