[Fixed]-Django –CSRF token missing or incorrect

10👍

Try adding the @csrf_protect decorator just before your login function.

from django.views.decorators.csrf import csrf_protect

@csrf_protect
def login(request):
     csrfContext = RequestContext(request)
     return render_to_response('foo.html', csrfContext)

If the form is not in foo.html then you need to add the @csrf_protect method to the view function that is generating it.

16👍

I had the same problem with you and i found this code that solve my problem.

from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render
from django.contrib import auth

#in accounts.forms i've placed my login form with two fields, username and password
from accounts.forms import LoginForm

@csrf_exempt
def login(request):
   if request.method == "POST":
      form = LoginForm(request.POST)
      if form.is_valid():
         user = auth.authenticate(
                username=form.cleaned_data["username"],
                password=form.cleaned_data["password"])
                auth.login(request, user)
                return HttpResponseRedirect("/")
      else:
         form = LoginForm()

return render(request, 'accounts/login.html', {'form':form})

1👍

Just add this line .

$.ajaxSetup({
    data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
});

0👍

You should do the following:

def login(request):
     context = {}
     request_context = RequestContext(request)
     return render_to_response('foo.html', context,
                               request_context=request_context)

Here are official docs for render_to_response.

0👍

Just add this in your HTML:

{% csrf_token %}
👤Tory

0👍

go urls and add the .as_view() next to the view metho/class
ex.

ObtainAuthTokenView.as_view()

0👍

While disabling the CSRF tokens and manually getting the CSRF token value would still have worked. But, in my case the syntax was not properly structured as in html we don’t worry about our script design but I think when using jinja i.e. Our templating language it matter’s and yes that’s how I solved my problem.

👤Chirag

Leave a comment