django login

| | Comments (0) | TrackBacks (0)

最近写一个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'),
    

0 TrackBacks

Listed below are links to blogs that reference this entry: django login.

TrackBack URL for this entry: http://mt.khsing.net/cgi-bin/mt-tb.cgi/55

Leave a comment

About this Entry

This page contains a single entry by Guixing published on February 3, 2009 2:48 PM.

易用的touchpad was the previous entry in this blog.

一个safari地址栏的小技巧 is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.