- Author:
- johnboxall
- Posted:
- June 4, 2009
- Language:
- Python
- Version:
- 1.0
- Score:
- 7 (after 7 ratings)
Sometimes the only way to reproduce a bug on a production site is to login as the User who encountered it. This form allows you to login as any user on the site.
Usage
@staff_member_required
def login_as(request, template="login_as.html"):
data = request.POST or None
form = LoginAsForm(data, request=request)
if form.is_valid()
form.save()
return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)
...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | from django.contrib.auth import login, get_backends
from django.contrib.auth.models import User
class LoginAsForm(forms.Form):
"""
Sometimes to debug an error you need to login as a specific User.
This form allows you to log as any user in the system. You can restrict
the allowed users by passing a User queryset paramter, `qs` when the
form is instantiated.
"""
user = forms.ModelChoiceField(User.objects.all())
def __init__(self, data=None, files=None, request=None, qs=None, *args,
**kwargs):
if request is None:
raise TypeError("Keyword argument 'request' must be supplied")
super(LoginAsForm, self).__init__(data=data, files=files, *args, **kwargs)
self.request = request
if qs is not None:
self.fields["user"].queryset = qs
def save(self):
user = self.cleaned_data["user"]
# In lieu of a call to authenticate()
backend = get_backends()[0]
user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
login(self.request, user)
message = "Logged in as %s" % self.request.user
self.request.user.message_set.create(message=message)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 3 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
This is awesome. Just what I needed. Thanks!
#
Please login first before commenting.