Skip to content

Instantly share code, notes, and snippets.

@hgdeoro
Last active July 10, 2022 12:20
Show Gist options
  • Save hgdeoro/3336947 to your computer and use it in GitHub Desktop.
Save hgdeoro/3336947 to your computer and use it in GitHub Desktop.
Automatically login 'admin' user in Django
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'utils.AutomaticLoginUserMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.transaction.TransactionMiddleware',
)
#
# This middleware tries to automatically login the 'admin' user
# using the 'admin' password. DON'T USE THIS IN A MULTI-USER SYSTEM...
# ...but this is of great help on development :-D
#
# You must create an user named 'admin', with password 'admin'
#
class AutomaticLoginUserMiddleware(object):
def process_request(self, request):
user = auth.authenticate(username='admin', password='admin')
if user:
request.user = user
auth.login(request, user)
#
# This version automatically creates the user
#
class AutomaticLoginUserMiddleware2(object):
def process_request(self, request):
if request.user.is_authenticated():
return
if not request.path_info.startswith('/admin'):
return
try:
User.objects.create_superuser('admin', 'admin@example.com', 'admin')
except:
pass
user = auth.authenticate(username='admin', password='admin')
if user:
request.user = user
auth.login(request, user)
@dreki
Copy link

dreki commented Apr 15, 2016

Helped me figure out how to create an admin user in an unattended environment. Thank you.

@xcriptus
Copy link

xcriptus commented Jun 28, 2017

Cool stuff.
Just for the record it should start with

from django.contrib.auth.models import User
from django.contrib import auth
from django.utils.deprecation import MiddlewareMixin   # see below

I had to add make the following changes (using django 1.10)

line 21: class AutomaticLoginUserMiddleware(MiddlewareMixin)

I got first an error when wsgi load the plugin. Complaining as (object()) does not have parameter. Looking at django source code, MiddlewareMix seems to be necessary.

I also had to change the order of middleware as below :

    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'utils.AutomaticLoginUserMiddleware',

otherwise request.user is not defined and I got various CSRF problems probably due to the fact that the token is changed when the user log again.
Now it works for me. Cool.

Thanks for your piece of code !

@nehapanchal2606
Copy link

please share a admin login nd with user login

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