在Django中限制已登录用户的访问的方法
有很多原因需要控制用户访问站点的某部分。
一个简单原始的限制方法是检查request.user.is_authenticated(),然后重定向到登陆页面:
fromdjango.httpimportHttpResponseRedirect defmy_view(request): ifnotrequest.user.is_authenticated(): returnHttpResponseRedirect('/accounts/login/?next=%s'%request.path) #...
或者显示一个出错信息:
defmy_view(request): ifnotrequest.user.is_authenticated(): returnrender_to_response('myapp/login_error.html') #...
作为一个快捷方式,你可以使用便捷的login_required修饰符:
fromdjango.contrib.auth.decoratorsimportlogin_required @login_required defmy_view(request): #...
login_required做下面的事情:
如果用户没有登录,重定向到/accounts/login/,把当前绝对URL作为next在查询字符串中传递过去,例如:/accounts/login/?next=/polls/3/。
如果用户已经登录,正常地执行视图函数。视图代码就可以假定用户已经登录了。
=