Last active
July 10, 2022 12:20
-
-
Save hgdeoro/3336947 to your computer and use it in GitHub Desktop.
Automatically login 'admin' user in Django
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# 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) |
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
Cool stuff.
Just for the record it should start with
I had to add make the following changes (using django 1.10)
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 :
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 !