在Django的实际应用中,我们通常会限制某些页面在登录后方可访问(如个人中心页面),否则就跳转到登录页面先进行登录。
在网上搜索到的直接使用装饰器@login_required放在view上方的做法当前版本(1.9.*以上)并不可用,会报以下错误:
1 | AttributeError: 'function' object has no attribute 'as_view' |
那么该如何实现呢?以index页面为例,实现方法有以下几种:
1.url+view文件
1 2 3 4 5 6 7 8 9 10 | #urls.py,以下xxx为书写view的app名称 from xxx.views import IndexView url(r '^$' , IndexView.as_view(), name= "index" ), #views.py from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator @method_decorator(login_required, name= 'dispatch' ) class IndexView(View): def get(self, request): return render(request, 'index.html' , {}) |
2.仅url文件
1 2 | from django.contrib.auth.decorators import login_required url(r '^$' , login_required(TemplateView.as_view(template_name= "index.html" )), name= "index" ), |
3.LoginRequiredMixin
1 2 3 4 5 6 7 8 9 | # views.py,以下xxx为书写view的app名称 from django.contrib.auth.mixins import LoginRequiredMixin class IndexView(LoginRequiredMixin, View): def get(self, request): return render(request, 'index.html' , {}) # urls.py from xxx.views import IndexView url(r '^$' , IndexView.as_view(), name= "index" ), |
注:默认登录页面为/accounts/login/,如需更改,请在settings.py文件中进行相应的更改,如
1 2 | #login_required URL LOGIN_URL = '/login/' |