禁止(403)CSRF验证失败.请求中止

use*_*786 8 django django-middleware django-views

我正在制作一个登录表单的应用程序,但是当我运行我的应用程序并单击登录按钮时,将发生以下错误

禁止(403)CSRF验证失败.请求中止.

view.py的代码如下:

from django.template import  loader
from django.shortcuts import render_to_response
from registration.models import Registration
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import redirect


def view_login(request,registration_id):
   t = loader.get_template('registration/login.html') 
   try:
         registration=Registration.objects.get(pk=registration_id)
   except Registration.DoesNotExist:
         return render_to_response("login.html",{"registration_id":registration_id})

def home(request,registration_id):
    if request.method == "POST":
      username = request.POST.get('user_name')
      password = request.POST.get('password')
      user = authenticate(username=username, password=password)
      if user is not None:
        if user.is_active:
          login(request, user)
        # success
          return render('registration/main_page.html',{'registration_id':registration_id},context_instance=RequestContext(user))
        else:
         #user was not active
           return redirect('q/',context_instance=RequestContext(user))
      else:
        # not a valid user
           return redirect('q/',context_instance=RequestContext(user))
    else:
       # URL was accessed directly
           return redirect('q/',context_instance=RequestContext(user))
Run Code Online (Sandbox Code Playgroud)

Muh*_*yis 19

对于那些使用或以上的用户,调用Django==4.*中必须有一个附加字段,并在此处添加您的域,问题已解决。settings.pyCSRF_TRUSTED_ORIGINS=[]

检查这个最新版本

  • 谢谢你!这对我来说是个问题。如何跟上这样的版本变化,您是否会在发布时专门阅读发行说明?即使使用 DEBUG=True ,该错误对我来说也没有任何帮助,我遇到你的答案纯粹是运气。 (2认同)

Blu*_*gma 16

您需要{% csrf_token %}在表单中添加

https://docs.djangoproject.com/en/1.4/ref/contrib/csrf/

像那样 :

<form>
    {% csrf_token %}
    <anything_else>
</form>
Run Code Online (Sandbox Code Playgroud)

此外,每次使用时都必须使用RequestContext(request)render_to_response:

return render_to_response("login.html",
    {"registration_id":registration_id},
    context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)

你必须导入身份验证和登录:

from django.contrib.auth import authenticate, login
Run Code Online (Sandbox Code Playgroud)


dar*_*1ne 12

Django \xe2\x89\xa5 4中,现在需要在settings.py中指定CSRF_TRUSTED_ORIGINS

\n
CSRF_TRUSTED_ORIGINS = [\'https://your-domain.com\', \'https://www.your-domain.com\']\n
Run Code Online (Sandbox Code Playgroud)\n

查看文档

\n