Showing posts with label remember-me. Show all posts
Showing posts with label remember-me. Show all posts

Saturday, May 16, 2009

How to add a "remember me" checkbox to django-registration

If you are using django-registration app, you might want to add a "remember me" checkbox to your login form. Usually, "remember me" functionality means that the cookie is set to expire for an extended period of time.

Create a view function inside your app:

from django.contrib.auth import views as auth_views
...
def login_user(request, template_name='registration/login.html', extra_context=None):
response = auth_views.login(request, template_name)
if request.POST.has_key('remember_me'):
request.session.set_expiry(1209600) # 2 weeks

This view practically calls Django's original login view function, and then checks if the request contains a "remember_me" field checked. Also, in the settings file, you should make sure to set SESSION_EXPIRE_AT_BROWSER_CLOSE = True to make the default behavior such that the cookie expires when the user closes the browser.

You should now edit your login template to add the checkbox to the login form:

...
<input type="checkbox" name="remember_me" value="true">Remember Me</input>
...

Last, you should hook you application url to the new login view we just defined. Edit you applications urls.py:

urlpatterns = patterns('',
...
url(r'^login/$', login_user, {'template_name': 'registration/login.html'}, name='auth_login'),