- Django's user authentication system provides a method
request.user.is_authenticated()
to determine whether the user is logged in. - This method returns True or by logging verification: return False.
class UserInfoView(View):
"""用户中心"""
def get(self, request):
"""提供个人信息界面"""
# 进行判断: 是否登录验证
if request.user.is_authenticated():
# 如果登录, 则正常加载用户中心页面
return render(request, 'user_center_info.html')
else:
# 否则, 进入登录页面,进行登录
return redirect(reverse('users:login'))
- Django's user authentication system provides
login_required
the decorator to determine whether the user is logged- The inside of the package
is_authenticate
- position:
django.contrib.auth.decorators
- The inside of the package
- Authentication by logging into the interior of the view, view logic performed
- It was not redirected to the login authentication via
LOGIN_URL
the configuration item specified address- Therefore, the use of the decorators, we need dev.py file, add the following settings:
LOGIN_URL = '/login/'
- Logged-on user to access, or access path
- Therefore, the use of the decorators, we need dev.py file, add the following settings:
login_required
usage
- Direct decorative function view
- as_view () method is to turn into a class view of the function of view, to use decorative decorator login_required view, return values indirect decorative as_view () method
# 在子路由中, 给 as_view() 函数,添加装饰器: url(r'^info/$', login_required(views.UserInfoView.as_view()), name='info'),
- View defined subclasses: a package login_required decorator
# 定义工具类: LoginRequired
# 继承自: View
class LoginRequired(View):
"""验证用户是否登陆的工具类"""
# 重写 as_view() 函数
# 在这个函数中, 对 as_view 进行装饰
@classmethod
def as_view(cls, **initkwargs):
# 我们重写这个方法, 不想做任何的修改操作
# 所以直接调用父类的 super().as_view() 函数.
view = super().as_view()
return login_required(view)
Our own view class, let it inherited from LoginRequired
class UserInfoView(LoginRequired):
"""用户中心接口"""
def get(self, request):
"""提供个人信息界面"""
return render(request, 'user_center_info.html')
- Not recommended : tools directly dependent on the view class View, so relatively poor reusability.
3. inherited from the object.
# 我们定义的工具类:
# 继承自 object
class LoginRequired(object):
"""验证用户是否登陆的工具类"""
# 重写该函数:
@classmethod
def as_view(cls, **initkwargs):
# 调用父类的 as_view() 方法
view = super().as_view()
# 添加装饰行为:
return login_required(view)
Define our own class view, it needs to inherit from: Tools + View
class UserInfoView(LoginRequired, View):
"""用户中心"""
def get(self, request):
"""提供个人信息界面"""
return render(request, 'user_center_info.html')