当用户未登录时,他应该被重定向到登录页面。保护未经身份验证的用户的网站
if not request.user.is_authenticated()
# redirect to the login page
但是这段代码必须写在每个视图中。只有一种方法可以为所有视图编写通用代码?
当用户未登录时,他应该被重定向到登录页面。保护未经身份验证的用户的网站
if not request.user.is_authenticated()
# redirect to the login page
但是这段代码必须写在每个视图中。只有一种方法可以为所有视图编写通用代码?
你可以用中间件的做到这一点:
class RequireLoginMiddleware(object):
def process_request(self, request):
if not request.user.is_authenticated():
return HttpResponseRedirect('/login/')
return None
当然,你不想这样做,登录页面本身:
class RequireLoginMiddleware(object):
def process_request(self, request):
if request.path.startswith('/login'):
return None
if not request.user.is_authenticated():
return HttpResponseRedirect('/login/')
return None
@login_required
修饰者怎么样? https://docs.djangoproject.com/en/dev/topics/auth/#the-login-required-decorator
强制性引用[Django书中'@ login_required'装饰器的注释](http://www.djangobook.com/en/1.0/chapter12/#cn137)。 –
难道你让你的授权使用类似.htaccess的服务器级别检查? –
不,它应该使用django – Deadly
你应该看看Django的书。如果你不想要一个物理副本,有一个[免费的在线版本](http://www.djangobook.com/en/1.0/)。它在[会话,用户和注册](http://www.djangobook.com/en/1.0/chapter12/)上有一个很好的部分,它提到了答案中提到的整洁的装饰器。 –