django - csrf验证失败请求被中断




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

我在使用1.1版本的“Django权威指南”一书时遇到了这个问题。 本书没有解决在更高版本中强制要求进行csrf_token验证的问题。

要解决此问题,请添加:

from django.template import RequestContext

到views.py文件和为render_to_response函数添加的参数:

context_instance = RequestContext(request)

请务必在模板的<form>标签中添加{% csrf_token %}

我正在做一个登录表单的应用程序,但是当我运行我的应用程序,然后单击登录按钮时,将出现以下错误

禁止(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))

只是评论'django.middleware.csrf.CsrfViewMiddleware'

在你的settings.py中 ,这对我有用:

//settings.py
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]