Skip to content

Instantly share code, notes, and snippets.

@dbrgn
Last active October 31, 2022 15:20
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dbrgn/bae5329e17d2801a041e to your computer and use it in GitHub Desktop.
Save dbrgn/bae5329e17d2801a041e to your computer and use it in GitHub Desktop.
Manually create a Django session
from django.contrib import auth
from django.contrib.sessions.backends.db import SessionStore
session = SessionStore(None)
session.clear()
session.cycle_key()
session[auth.SESSION_KEY] = user._meta.pk.value_to_string(user)
session[auth.BACKEND_SESSION_KEY] = 'django.contrib.auth.backends.ModelBackend'
session[auth.HASH_SESSION_KEY] = user.get_session_auth_hash()
session.save()
@dbrgn
Copy link
Author

dbrgn commented Jan 26, 2016

Only use this for testing, not for production systems!

@drozdowsky
Copy link

drozdowsky commented Nov 14, 2017

Really helped me :D Thanks
BTW, why not use this on production server?

@koxu1996
Copy link

Thank you for sharing this 👍

@RealOrangeOne
Copy link

Worth noting this is totally fine for production, as it very closely matches how Django does it (https://github.com/django/django/blob/3f2821af6bc48fa8e7970c1ce27bc54c3172545e/django/contrib/auth/__init__.py#L126), just that Django has a few more checks around the incoming data. If you need a session to impersonate a user programmatically, this is a good way to go!

@andriiholovko
Copy link

Worked for me, GJ!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment