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.*)/$', 'my_app.views.su', {'redirect_url': '/'}), )