Switching the Logged-in User in Django Using the Django Shell
Django
2023-10-12 12:41 (2 years ago)
How to Force Login as Another User for Inquiry Handling
When performing actions such as handling inquiries, be extremely cautious as incorrect operations or leaving the session logged in as another user can be dangerous. Do not perform these actions in a production environment.
The author assumes no responsibility for any impacts, damages, or issues that arise from performing these actions.
- First, log in to the Django application using your browser.
- Record the
session_idfrom the cookies. - Execute
./manage.py shellon the server.
# Your own session_id
session_id = 'abcd1234xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
# ID of the user you want to impersonate
user_id = 1
from django.conf import settings
from user.models import User
engine = __import__(settings.SESSION_ENGINE, {}, {}, [''])
session = engine.SessionStore(session_id)
dict(session) # Confirm your own user ID
user = User.objects.get(id=user_id)
user # Verify the user details
session['_auth_user_id'] = user.id
session['_auth_user_hash'] = user.get_session_auth_hash()
session.save()
Reload the browser, and you should be logged in as the desired user.
After completing the verification tasks, make sure to delete the cookies and log back in with the regular user to avoid any accidents.
Please rate this article
Current rating: 5.0 (1)
The author runs the application development company Cyberneura.
We look forward to discussing your development needs.
We look forward to discussing your development needs.