Django --CSRF token missing or incorrect

2020-07-10 09:10发布

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)

标签: python django
5条回答
太酷不给撩
2楼-- · 2020-07-10 09:57

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.

查看更多
狗以群分
3楼-- · 2020-07-10 10:07

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

ObtainAuthTokenView.as_view()

查看更多
一夜七次
4楼-- · 2020-07-10 10:08

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})
查看更多
爷、活的狠高调
5楼-- · 2020-07-10 10:13

Just add this in your HTML:

{% csrf_token %}
查看更多
姐就是有狂的资本
6楼-- · 2020-07-10 10:15

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.

查看更多
登录 后发表回答