如何在django 1.11中导入和使用csrf标记?

sup*_*dr1 2 python django

Pease帮助在django 1.11中使用csrf标记

在view.py我使用以下代码:

from django.shortcuts import render_to_response, redirect
from django.contrib import auth
from django.views.decorators.csrf import csrf

def login(request):
    args = {}
    args.update(csrf(request))
    if request.POST:
            username = request.POST.get('username', '')
            password = request.POST.get('password', '')
            user = auth.authenticate(username=username, password=password)
            if user is not None:
                    auth.login(request, user)
                    return redirect('/')
            else:
                    args['login_error'] = '???????????? ?? ??????';
                    return render_to_response('login.html', args)
    else:
            return render_to_response('login.html', args)
Run Code Online (Sandbox Code Playgroud)

但控制台显示按照错误消息:

文件"/home/kalinin/django/login/views.py",第3行,来自django.views.decorators.csrf import csrf ImportError:无法导入名称'csrf'

在django 1.8我使用类似的代码,但导入csrf:

from django.core.context_processors import csrf
Run Code Online (Sandbox Code Playgroud)

和应用程序运行没有问题

请帮助运行我的django 1.11应用程序

Ala*_*air 6

在Django 1.8中,模板上下文处理器被移动到django.template.context_processors.csrf,因此导入将是:

from django.template.context_processors import csrf
Run Code Online (Sandbox Code Playgroud)

但是,您根本不需要导入它.停止使用render_to_response,它已经过时了.请改用render快捷方式.

from django.shortcuts import render

return render(request, 'login.html', args)
Run Code Online (Sandbox Code Playgroud)

使用render快捷方式时,您无需担心csrf视图中的令牌,并且可以删除此行.

args.update(csrf(request))
Run Code Online (Sandbox Code Playgroud)