扒Django Admin的登陆界面出来用

最近写一个django项目的时候犯懒,把admin的login form给简单的扒出来用了用,感觉还不错。

先把display_login_form给扒出来

def display_login_form(request, error_message='', extra_context=None):
request.session.set_test_cookie()
context = {
'title': 'Log in',
'app_path': request.get_full_path(),
'error_message': error_message,
'root_path': '',
}
context.update(extra_context or {})
return render_to_response('admin/login.html', context,
context_instance=template.RequestContext(request)
)

然后自己再写一个login

def login(request):
if request.POST:
username = request.POST['username']
password = request.POST['password']
user = auth.authenticate(username=username, password=password)
if user is not None and user.is_active:
auth.login(request, user)
return http.HttpResponseRedirect(request.get_full_path())
else:
return display_login_form(request,"Login error!")
else:
return display_login_form(request)

需要认证的地方就这样写

def login_test(request):
if not request.user.is_authenticated():
return login(request)
else:
return http.HttpResponse("Welcome %s" % request.user)

update: 上面那个方法还是不够懒,细读了一下文档,可以这样写。

  • settings.py
LOGIN_URL = '/login/'
LOGIN_REDIRECT_URL = '/'

  • urls.py
(r'^login/','django.contrib.auth.views.login',{'template_name': 'admin/login.html'}),
(r'^logout/','superman.lib.views.logout'),


Last modified on 2009-02-03