14

So I am getting Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: CSRF token missing or incorrect.
I have the 'django.middleware.csrf.CsrfViewMiddleware', in my middleware_classes. Here is my template

<form name="input" action="/login/" method="Post"> {% csrf_token %}
<input type="submit" value="Submit"></form>

Here is my view

from django.shortcuts import render_to_response
from django.core.context_processors import csrf
from django.template import RequestContext
def login(request):
     csrfContext = RequestContext(request)
     return render_to_response('foo.html', csrfContext)

Well I am new to Django and most web development, but I cannot seem to find the problem here. Any help would be much appreciated!

Also i have tried the method in the django documentation

c = {}
c.update(csrf(request))
# ... view code here
return render_to_response("a_template.html", c)
Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
daabears
  • 143
  • 1
  • 1
  • 4
  • 2
    Just a side note: if you're new to Django, I would look at using class-based views for just about everything. Even if you just override `post`, they at least enforce which HTTP request types the server will respond to. – Arion Oct 04 '12 at 16:27
  • What template/view is the
    being created in?
    – Nathan Villaescusa Oct 04 '12 at 17:01
  • 2
    you need to add, `{% csrf_token %}` in the template. and make sure that `RequestContext` is present.. and of course, the respective middleware in `settings.py` and.. if the problem still persists. I am not sure but.. try something `@csrf_exempt` decorators.. etc – Surya Oct 04 '12 at 17:03

7 Answers7

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})
CodeArtist
  • 5,534
  • 8
  • 40
  • 65
  • 10
    adding csrf_exempt should not be necessary for this and makes your site vulnerable. That decorator exists for edge cases where you specifically need those kinds of requests, are aware of the risks, and have taken other precautions. – Andre Sep 17 '13 at 11:07
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.

Nathan Villaescusa
  • 17,331
  • 4
  • 53
  • 56
  • Tried it and still getting the same error, Also tried the suggestion above, fixing the render_to_response syntax... – daabears Oct 04 '12 at 16:34
  • Could the problem be that you are posting to /login/ from a different page and that the other page doesn't have @csrf_protect on it? What page is the template text in your comment from? Take a look at the HTML that is being generated and verify that it has the csrf_protect token in it. – Nathan Villaescusa Oct 04 '12 at 16:44
  • This worked for me, the key is making sure a crf cookie is being generated – sgDysregulation Apr 25 '23 at 07:54
1

Just add this line .

$.ajaxSetup({
    data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
});
Wahib Mzali
  • 120
  • 5
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.

miki725
  • 27,207
  • 17
  • 105
  • 121
  • Still getting the same error, I also tried using the @csrf_protect decorator with no improvement... – daabears Oct 04 '12 at 16:33
  • In your html, are you seeing the csrf token? If not, try adding `requires_csrf_token` decorator. – miki725 Oct 04 '12 at 16:59
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.

Community
  • 1
  • 1
Chirag
  • 1
  • 2
-1

Just add this in your HTML:

{% csrf_token %}
Pingolin
  • 3,161
  • 6
  • 25
  • 40
Tory
  • 1
  • 2
  • 1
    whereas this solution does not answer the above question, it does work for someone who is sending a form without '{% csrf_token %}' – Odwori Feb 03 '22 at 17:43