Django提交POST表单报”CSRF verification failed.”

  • A+
所属分类:Blog python

环境

  • 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!')

再次执行,运行正常

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: