手机
当前位置:查字典教程网 >脚本专栏 >python >在Django中限制已登录用户的访问的方法
在Django中限制已登录用户的访问的方法
摘要:有很多原因需要控制用户访问站点的某部分。一个简单原始的限制方法是检查request.user.is_authenticated(),然后重定...

有很多原因需要控制用户访问站点的某部分。

一个简单原始的限制方法是检查 request.user.is_authenticated() ,然后重定向到登陆页面:

from django.http import HttpResponseRedirect def my_view(request): if not request.user.is_authenticated(): return HttpResponseRedirect('/accounts/login/?next=%s' % request.path) # ...

或者显示一个出错信息:

def my_view(request): if not request.user.is_authenticated(): return render_to_response('myapp/login_error.html') # ...

作为一个快捷方式, 你可以使用便捷的 login_required 修饰符:

from django.contrib.auth.decorators import login_required @login_required def my_view(request): # ...

login_required 做下面的事情:

如果用户没有登录, 重定向到 /accounts/login/ , 把当前绝对URL作为 next 在查询字符串中传递过去, 例如: /accounts/login/?next=/polls/3/ 。

如果用户已经登录, 正常地执行视图函数。 视图代码就可以假定用户已经登录了。

=

【在Django中限制已登录用户的访问的方法】相关文章:

python批量导出导入MySQL用户的方法

Python中针对函数处理的特殊方法

Python中使用中文的方法

Python中文件遍历的两种方法

python二叉树遍历的实现方法

Python 条件判断的缩写方法

python 不关闭控制台的实现方法

Python调用C/C++动态链接库的方法详解

Python生成pdf文件的方法

python的正则表达式re模块的常用方法

精品推荐
分类导航