Skip to content

Instantly share code, notes, and snippets.

@readevalprint
Created December 14, 2011 19:49
Show Gist options
  • Save readevalprint/1478160 to your computer and use it in GitHub Desktop.
Save readevalprint/1478160 to your computer and use it in GitHub Desktop.
Log in as a user in Django
from django.shortcuts import get_object_or_404
from django.contrib.auth import SESSION_KEY
from django import http
from django.contrib.auth.models import User
from django.contrib.auth.decorators import user_passes_test
@user_passes_test(lambda u: u.is_staff)
def su(request, username, redirect_url='/'):
su_user = get_object_or_404(User, username=username)
if su_user.is_active:
request.session[SESSION_KEY] = su_user.id
return http.HttpResponseRedirect(redirect_url)
# In urls.py
from django.conf.urls.defaults import url
urlpatterns += patterns('',
url(r'^su/(?P<username>.*)/$', 'my_app.views.su', {'redirect_url': '/'}),
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment