CSRF verification failed. Request aborted
Solution 1:
You may have missed adding the following to your form:
{% csrf_token %}
Solution 2:
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})
Solution 3:
When you found this type of message , it means CSRF token missing or incorrect. So you have two choices.
-
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.
-
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',
)
Solution 4:
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..