环境
- python 3.6
- Django 2.0
- PyCharm 2017.2
问题
当提交POST表单时,出现以下报错: CSRF verification failed. Request aborted.
解决方法
- 查看setting.py,是否有
'django.middleware.csrf.CsrfViewMiddleware'
:
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',
]
- 在表单处理函数文件头导入csrf_protect:
from django.views.decorators.csrf import csrf_protect
- 在表单处理函数前加
@csrf_protect
:
@csrf_protect
def login(request):
if request.method=='GET':
return render(request,"login.html")
else:
print(request.GET)
print(request.POST)
user=request.POST.get("user")
pwd=request.POST.get("pwd")
if user == 'shunzi' and pwd == '123456':
return HttpResponse('登录成功')
else:
return HttpResponse('username or password is error!')
再次执行,运行正常
继续阅读
您可以选择一种方式赞助本站
支付宝扫一扫赞助
微信钱包扫描赞助
赏