Django未登录跳转登录页面设置

Coding Alan 7年前 (2017-03-13) 8744次浏览 0个评论 扫描二维码

在Django的实际应用中,我们通常会限制某些页面在登录后方可访问(如个人中心页面),否则就跳转到登录页面先进行登录。

在网上搜索到的直接使用装饰器@login_required放在view上方的做法当前版本(1.9.*以上)并不可用,会报以下错误:

AttributeError: 'function' object has no attribute 'as_view'

那么该如何实现呢?以index页面为例,实现方法有以下几种:

1.url+view文件

#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文件

from django.contrib.auth.decorators import login_required
url(r'^$', login_required(TemplateView.as_view(template_name="index.html")), name="index"),

3.LoginRequiredMixin

# 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文件中进行相应的更改,如

#login_required URL
LOGIN_URL = '/login/'
喜欢 (3)
[]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址