方法一
from django.template import RequestContext from django.shortcuts import render_to_response from django.http import HttpResponseRedirect def index(request): if not request.user.is_authenticated(): return HttpResponseRedirect('/accounts/login/') return render_to_response('login/index.html', context_instance=RequestContext(request))
方法二
from django.template import RequestContext from django.shortcuts import render_to_response from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login_required @login_required(login_url='/accounts/login') def index(request): if not request.user.is_authenticated(): return HttpResponseRedirect('/accounts/login/') return render_to_response('login/index.html', context_instance=RequestContext(request))
方法三
django-stronghold:试过将 login_required 装饰器四处乱放? 令所有 Django 视图有默认 login_required 呗。
只需要把你的登录视图添加上@public (否则就是死循环)
from stronghold.decorators import public @public def login(request): ....
参照https://github.com/mgrouchy/django-stronghold