Django提交POST表单“CSRF verification failed. Request aborted”问题的解决

时间:2022-04-11 06:34:50

1、环境

python 3.4

Django 1.7

Visual Studio 2015 PTVS

2、问题

提交表单,出现以下错误:

CSRF verification failed. Request aborted.

3、解决

查看settings.py, 有 'django.middleware.csrf.CsrfViewMiddleware' 一句:

 1 MIDDLEWARE_CLASSES = (
 2     'django.contrib.sessions.middleware.SessionMiddleware',
 3     'django.middleware.common.CommonMiddleware',
 4     'django.middleware.csrf.CsrfViewMiddleware',
 5     'django.contrib.auth.middleware.AuthenticationMiddleware',
 6     'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 7     'django.contrib.messages.middleware.MessageMiddleware',
 8     'django.middleware.clickjacking.XFrameOptionsMiddleware',
 9     'cstnet.middleware.urlsfilter',
10     'jobfarm.middleware.MultipleProxyMiddleware',
11     'jobfarm.middleware.OAuthJobFarmFilter'
12 )

在表单处理函数前添加 @csrf_protect :

 1 #申请表单处理
 2 @csrf_protect
 3 def doapply(request):
 4     context = {
 5         'group':request.POST['group'],
 6         'host':request.POST['host'],
 7         'image':request.POST['image'],
 8         'net':request.POST['net'],
 9         'vcpu':request.POST['vcpu'],
10         'num':request.POST['num'],
11         'remarks':request.POST['remarks']    
12     };
13 ...

并在文件头导入命名空间,不然会找不到csrf_protect:

1 from django.views.decorators.csrf import csrf_protect

运行正常。