Unable log in to the django admin page with a valid username and password
Asked Answered
B

26

81

I can’t log in to the django admin page. When I enter a valid username and password, it just brings up the login page again, with no error messages

This question is in the django FAQ, but I've gone over the answers there and still can't get past the initial login screen.

I'm using django 1.4 on ubuntu 12.04 with apache2 and modwsgi.

I've confirmed that I'm registering the admin in the admin.py file, made sure to syncdb after adding INSTALLED_APPS. When I enter the wrong password I DO get an error, so my admin user is being authenticated, just not proceeding to the admin page.

I've tried both setting SESSION_COOKIE_DOMAIN to the machine's IP and None. (Confirmed that the cookie domain shows as the machine's IP in chrome)

Also, checked that the user authenticates via the shell:

>>> from django.contrib.auth import authenticate
>>> u = authenticate(username="user", password="pass")
>>> u.is_staff
True
>>> u.is_superuser
True
>>> u.is_active 
True

Attempted login using IE8 and chrome canary, both results in the same return to the login screen.

Is there something else I'm missing????

settings.py

...
MIDDLEWARE_CLASSES = (
    'django.middleware.gzip.GZipMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.middleware.transaction.TransactionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)
AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',)
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.admin',    
    'django.contrib.staticfiles',
    'django.contrib.gis',
    'myapp.main',
)

SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_SAVE_EVERY_REQUEST = True
SESSION_COOKIE_AGE = 86400 # sec
SESSION_COOKIE_DOMAIN = None
SESSION_COOKIE_NAME = 'DSESSIONID'
SESSION_COOKIE_SECURE = False

urls.py

from django.conf.urls.defaults import * #@UnusedWildImport
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin

admin.autodiscover()

urlpatterns = patterns('',
    (r'^bin/', include('myproject.main.urls')),    
    (r'^layer/r(?P<layer_id>\d+)/$', "myproject.layer.views.get_result_layer"),
    (r'^layer/b(?P<layer_id>\d+)/$', "myproject.layer.views.get_baseline_layer"),
    (r'^layer/c(?P<layer_id>\d+)/$', "myproject.layer.views.get_candidate_layer"),    
    (r'^layers/$', "myproject.layer.views.get_layer_definitions"),
    (r'^js/mapui.js$', "myproject.layer.views.view_mapjs"),
    (r'^tilestache/config/$', "myproject.layer.views.get_tilestache_cfg"),
    (r'^admin/', include(admin.site.urls)),  
    (r'^sites/', include("myproject.sites.urls")),  
    (r'^$', "myproject.layer.views.view_map"),
)


urlpatterns += staticfiles_urlpatterns()

Apache Version:

Apache/2.2.22 (Ubuntu) mod_wsgi/3.3 Python/2.7.3 configured

Apache apache2/sites-available/default:

<VirtualHost *:80>
        ServerAdmin ironman@localhost
        DocumentRoot /var/www/bin
        LogLevel warn
        WSGIDaemonProcess lbs processes=2 maximum-requests=500 threads=1
        WSGIProcessGroup lbs
        WSGIScriptAlias / /var/www/bin/apache/django.wsgi
        Alias /static /var/www/lbs/static/
</VirtualHost>
<VirtualHost *:8080>
        ServerAdmin ironman@localhost
        DocumentRoot /var/www/bin
        LogLevel warn
        WSGIDaemonProcess tilestache processes=2 maximum-requests=500 threads=1
        WSGIProcessGroup tilestache
        WSGIScriptAlias / /var/www/bin/tileserver/tilestache.wsgi
</VirtualHost>

UPDATE

The admin page does proceed when using the development server via runserver so it seems like a wsgi/apache issue. Still haven't figured it out yet.

SOLUTION

The problem was that I had the settings file SESSION_ENGINE value set to 'django.contrib.sessions.backends.cache' without having the CACHE_BACKEND properly configured.

I've changed the SESSION_ENGINE to 'django.contrib.sessions.backends.db' which resolved the issue.

Bootlace answered 10/8, 2012 at 2:45 Comment(17)
Can you paste your urls.py as well?Pasticcio
Have you tried moving django.middleware.csrf.CsrfViewMiddleware before django.contrib.auth.middleware.AuthenticationMiddleware ?Savoirfaire
Does it work when you're running it from ./manage.py runserver (i.e. not over mod_wsgi)?Lafontaine
Are you actually failing to authenticate? You could be 'logged in' but still looking at the login form.Schuyler
@JohnMee I've tried using the url /admin/app/ after I having been returned to the login screen and it still brings up the login screen.Bootlace
@Brandon I just tried putting csrf before auth and it still brings me back to the login screen.Bootlace
Hmm. Are you sure this isn't an issue related to cookies? I've had instances where I forgot to set SESSION_COOKIE_SECURE = False in my local_settings.py and the admin login won't allow me in. Have you tried removing all of the .pyc files? Maybe some old code is hanging around.Savoirfaire
Just checked again, "SESSION_COOKIE_SECURE = False" is in the settings file. I deleted the settings.pyc file and restarted apache, and still the same...Bootlace
Does you user is_active? Also post console output, when you try to loginMurtha
@Bootlace could you try it without WSGI in the equation (see above)?Lafontaine
Agree with supervacuo, let's run it with the dev server to exclude wsgi, apache, ... as source of troubleRiti
Are you running this on your local machine or as a valid domain? If it's a domain, try setting the SESSION_COOKIE_DOMAIN setting to that instead of your computer's IP address. If it's on your local machine, try setting it to the loopback address of 127.0.0.1.Saddle
@Lafontaine yes, I just confirmed that using runserver it does proceed pass the login screen.Bootlace
Do apache error/access logs show anything? If it is a WSGI issue, there may be permission issues with some of your importsBalladeer
You could at least show the mod_wsgi configuration to confirm you are doing the right thing there.Pero
@Balladeer no unfortunately, there is nothing in the apache error log to point me anywhere.Bootlace
@GrahamDumpleton thanks for mentioning that, I've added the apache config above.Bootlace
B
72

Steps to debug:

  • Make sure that your Database is synced
    • Double check that you have a django_session table
  • Try to authenticate
    • Do you see a record being created in the django_session table?

IF NOT

  • remove non-standard settings
    • AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',)
    • SESSION_EXPIRE_AT_BROWSER_CLOSE = True
    • SESSION_SAVE_EVERY_REQUEST = True
    • SESSION_COOKIE_AGE = 86400 # sec
    • SESSION_COOKIE_DOMAIN = None
    • SESSION_COOKIE_NAME = 'DSESSIONID'
    • SESSION_COOKIE_SECURE = False
  • Make sure that your Database is synced
    • Double check that you have a django_session table
  • Try to authenticate
    • Do you see a record being created in the django_session table?

Let me know if this turns up any useful debug.

Sample settings file: https://github.com/fyaconiello/Django-Blank-Bare-Bones-CMS/blob/master/dbbbcms/settings.py

Blameful answered 24/8, 2012 at 13:39 Comment(13)
Thanks, I've checked the session table, and it appears that an entry is not created. I double-checked and my settings are the same as you've posted above, and I'm seeing no entry in the table.Bootlace
Ok, this pointed me in the right direction. As suspected it was a mis-configuration on my part. the SESSION_ENGINE value was set to 'django.contrib.sessions.backends.cache' without having the CACHE_BACKEND properly configured. I've changed the SESSION_ENGINE to 'django.contrib.sessions.backends.db' which resolved the issue.Bootlace
Like @daigorocub, I only had to do SESSION_COOKIE_SECURE = False. Apparently when this is set to True and the connection is not over HTTPS (typical for a dev setup), the login can't be noted since there is no session cookie, so you are directed to log in again. Seems like there should be an error when the setting requires secure cookies and the connection isn't secure - kind of a big red flag that your network security is messed up - but it did solve the immediate problem with logging into admin.Savil
In my case, I was using RemoteUserBackend for authentication, but I had forgotten to configure Nginx to set REMOTE_USER on the machine that wasn't working.Muntin
Had a similar issue recently, where I was running multiple django projects on the same server on different ports. In this case I needed to make sure that the SESSION_COOKIE_NAME and CSRF_COOKIE_NAME were different per project served.Bootlace
Commenting out this AUTHENTICATION_BACKENDS = ['Authentication.backends.EmailBackend'] worked for me. But does that mean i have to always comment it out whenever i have to login to django admin ?Sermon
What to do if a record is not being created in the django_session table?Mcalister
Thx, checking session settings helped in my case :)Potboiler
Just wanted to chime in and say that I had the same problem with SESSION_ENGINE set to 'django.contrib.sessions.backends.cache' without configuring the CACHE backend. Thanks!Forbidding
@Forbidding glad you found this useful, the post is getting a little dated. I'm not even positive that the SESSION_ENGINE setting existed on the version of Django i was using when i posted this.Blameful
I tried with SESSION_COOKIE_SECURE = False. It is working fine with django==1.11.6 and python 3.5.2Stickle
I had an invalid SESSION_COOKIE_DOMAIN setting that didn't match my server environment. Session cookies were successfully written to the database, but I was always bounced back to the login page. Removing my custom setting solved the issue.Heighten
SESSION_COOKIE_SECURE = False Add this in your setting file and it removes other session-related code from the setting file then you try login in Django adminRowlock
G
23
>>> from django.contrib.auth import authenticate
>>> u = authenticate(username="user", password="pass")
>>> u.is_staff = True
>>> u.is_superuser = True

Is there something else I'm missing?

u.is_active should be True

Gavriella answered 23/8, 2012 at 9:40 Comment(2)
For me is_staff was strangely FalseYukikoyukio
@BurhanKhalid Its u.is_staff = True you have a missing equal signSermon
D
14

I had this problem. The issue is that in production I set two variables to True that allowed me to connect to the site using https.

SESSION_COOKIE_SECURE and CSRF_COOKIE_SECURE should be set to False if you are developing on localhost http. Changing these two variables to False allowed me to sign into the admin site when developing locally.

Doloroso answered 20/5, 2018 at 16:2 Comment(0)
W
4

After not being able to log in myself, I saw in the comment above someone mentioned about removing non-standard settings.

Adding this to my local settings solved it for me

SESSION_COOKIE_SECURE = False

Warmup answered 10/7, 2019 at 16:5 Comment(1)
That worked for me, however the deployment checklist says that this should be set to True for deployment. How do get the panel to work with this being set to True? docs.djangoproject.com/en/3.0/howto/deployment/checklistTardigrade
J
3

I don't believe the admin password is stored in the settings.py file. It's created when you first syncdb. I am thinking you either skipped creating the superuser or just made a typo. Try running in terminal at your projects root.:

python django-admin.py createsuperuser

That will allow you to retype your admin login. Also seen here https://docs.djangoproject.com/en/dev/ref/django-admin/

Jacket answered 12/8, 2012 at 2:48 Comment(3)
OP can authenticate in the shell, so this isn't it.Toper
Whoops. I didn't see that part. I've got nothing then :(Jacket
isn't that ./manage.py createsuperuser (that's what worked for me)Natheless
T
3

Did you try by creating the user with :

python manage.py createsuperuser

I have the same issue when I create the db on a test machine and migrate it to the deployment server...

Thereof answered 25/8, 2012 at 8:38 Comment(1)
Thanks, I did try to create another superuser with this method and attempt to login, but I'm still having the same problem.Bootlace
H
3

We had a similar issue in our app and these might help:

  1. Use cleanup command to clear older sessions from django_sessions

  2. Check the cookie size in firefox(firebug) or chrome developer tools. Because messaging is enabled by default in admin(django.contrib.messages.middleware.MessageMiddleware), the cookie size sometimes get larger than 4096 bytes with multiple edits and deletes. One quick test is to delete the "message" cookie and see if you can login after that.

And we actually ended up switching to nginx/uwsgi route because of this and other memory related issues with apache. Haven't seen this repeated in nginx since.

Hydrobomb answered 28/8, 2012 at 8:36 Comment(0)
O
2

sounds like a session problem because after the post you get redirected and immediately the system has forgotten that you logged in.

try the following:

  1. check your session backend is working.
  2. swap it with cache backend if you use db cache backend to check if transaction middleware is messing around.
  3. try db backend and check if there are sessions stored in the db table
Obstruct answered 23/8, 2012 at 9:34 Comment(0)
C
2

This is not OP's issue, but I am posting this answer in the hopes someone may have gone down the same path as I and arrived at this question as a result.

I came back to an old codebase after a year and was denied access to the admin panel despite all of the usual checks passing (user is present, nothing looks incorrect in the database, all debug modes are on, etc). Unfortunately, I had forgotten that the admin sign in page was not at the usual /admin route, but rather at an alternate route. The /admin page was a fake sign in page that always resulted in a failed sign in.

This setup was created using the app django-admin-honeypot.

Christhood answered 19/12, 2021 at 4:44 Comment(0)
D
1

I'm not exactly sure, but the problem might be with your URL configuration, concretely in these two lines:

(r'^admin/', include(admin.site.urls)),  
(r'^sites/', include("myproject.sites.urls")),

A longer time ago, I had trouble with browsing the admin of my Django project because a single URL configuration overwrote a part of the admin url. It seems that Django doesn't like it when you specify a custom URL configuration that contains elements which are also part of the admin URL. In your case, you have the app django.contrib.sites enabled in your settings.py. You can access the admin panel of this app by going to http://127.0.0.1:8000/admin/sites/. It might be that your URL configuration with r'^sites/' in it overrides a part of the admin url. Try renaming this specific URL configuration or disable django.contrib.sites in INSTALLED_APPS for testing purposes.

Please note that this is just an assumption. All I know is that Django's admin panel is a bit picky about URL configurations using similar names like its own URLs. I cannot test it myself at the moment. But maybe this helps you a bit.

Disciplinarian answered 22/8, 2012 at 17:23 Comment(0)
R
1

Checking some other articles on this topic, it could be related to sys.path. Can you check and compare sys.path when running the dev server and when running WSGI.

For some details, have a look this and that article. But I would check the sys.path first, before going into the details of this article.

Riti answered 23/8, 2012 at 9:57 Comment(0)
G
1

Check that you have at least one site to work with.

>>> from django.contrib.sites.models import Site
>>> Site.objects.count()
(0.048) SELECT COUNT(*) FROM `django_site`; args=()
1

If you see 0 here - create one.

Gallows answered 27/8, 2012 at 11:16 Comment(3)
Thanks, when there wasn't a site created there was an error being shown, so I did create one.Bootlace
@Bootlace So, now everything is ok?Gallows
no, I resolved this issue before having the problem mentioned here.Bootlace
I
1

Make sure your database user table having following entry is true:

is_staff  => True  (if exit).
is_active  => True .
is_superuser => True.
Ician answered 27/9, 2018 at 10:12 Comment(0)
A
1

For me below settings worked on localhost

AUTHENTICATION_BACKENDS = [
   'django.contrib.auth.backends.ModelBackend',
]

SESSION_COOKIE_DOMAIN = None
SESSION_ENGINE = 'django.contrib.sessions.backends.db'
Ahoy answered 14/1, 2023 at 8:36 Comment(0)
T
0

Disclaimer: I cannot add comments yet, so I have to ask clarification here proposing a solution at the same time. Sorry for that.

Is the user logged-out immediately after logging-in? something like this issue

You can check it in many ways, I suggest to add a hook to the logout signal (you can put it in your models.py):

from django.contrib.auth.signals import user_logged_out

def alertme(sender, user, request, **kwargs):
    print ("USER LOGGED OUT!") #or more sophisticate logging

user_logged_out.connect(alertme)

then try to log in and check if the message appears in your console. If it appears, then you have to check if you have a redirect or a customized template calling logout after login. Hope it helps you find the issue.

Telepathy answered 22/8, 2012 at 15:46 Comment(0)
R
0

I had same problem and it was just solved after restarting server :

systemctl restart nginx
Rictus answered 16/6, 2016 at 8:3 Comment(0)
E
0

You can ensure, the created user has been flagged as Is_staff = True, I sometimes forget to flag this to allow users to login to django admin

Engram answered 13/12, 2016 at 12:20 Comment(0)
I
0

I had a related issue where I'd try to log in and the page would hang before the socket would eventually be killed. It turned out that I was indeed being logged in, but one of the login signal processors was freezing.

Celery couldn't pass its asynchronous tasks to RabbitMQ because the RabbitMQ server wasn't able to start.

Iives answered 9/2, 2018 at 21:9 Comment(0)
C
0

For me, I could not login to the admin page in firefox but could login in chrome. The problem was that I had CSRF_COOKIE_PATH set in my settings.py. Never use that. It does not not work properly on django 1.8.

Craiova answered 9/3, 2018 at 18:32 Comment(0)
S
0

What I did was to navigate manually to the url I wanted to visit. So like: http://wildlifeapi.herokuapp.com/admin/ was returning the awful Heroku application error.

So what I did was to visit http://wildlifeapi.herokuapp.com/admin/api/animal/ and BINGO! it worked.

The funny thing is that it works well on my phone. It's probably a django redirection bug.

Salmon answered 31/1, 2020 at 11:1 Comment(0)
I
0

My issue was that My Admin Page was not loading and not working. Here is what I did:

pip uninstall django
pip install django==2.2

For more Detail Check Django Documentation.

Increment answered 31/5, 2020 at 6:23 Comment(0)
N
0

For anyone who encountered this problem after upgrading Django, the problem could be that the signature of the authenticate function has changed at some point. If the signature doesn't match what's expected, the backend is just ignored. So make sure your custom authentication backend authenticate method looks like this:

class EmailUsernameAuthenticationBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
       # ...

And NOT like this (without the request argument):

class EmailUsernameAuthenticationBackend(ModelBackend):
    def authenticate(self, username=None, password=None, **kwargs):
Ninanincompoop answered 20/9, 2021 at 10:59 Comment(0)
O
0

A bit late for the party, but to me it was different and surprinsingly simpler: for whatever reason my superuser account was gone so, obviously, the solution was I had to create it again.
I'm 99% sure I had executed migrate and makemigrations a few times after having created my superuser, but go figure...

It took me about a whole hour to finally figure it out, however. None of the variables discussed here existed in my settings.py -and still don't to the present moment- (probably because it has been nearly 10 years, so things might have changed considerably), like SESSION_ENGINE, SESSION_COOKIE_DOMAIN, CACHE_BACKEND, django_session table...
Also, Django's FAQ on this subject mentions checking if my account is_active and is_staff, but unfortunately without ever mentioning how to do it.

Oribelle answered 13/1, 2022 at 11:57 Comment(0)
T
0

For my case it is always the issue with SESSION_COOKIE_DOMAIN: On local machine I set it like:

SESSION_COOKIE_DOMAIN = 'localhost'

On remote one, domain one, like:

SESSION_COOKIE_DOMAIN = 'yourdomainname.com'
Tizes answered 27/12, 2022 at 13:44 Comment(0)
A
0

In my case, I was not able to log in because I was using email in the place of username (which in my case was "admin") to try to log in. So do ensure you're using the right username and password to log in

Artificer answered 3/1, 2023 at 19:8 Comment(0)
S
-1

Use some other virtual environment.it worked for me when i used conda environment.

Spill answered 5/12, 2019 at 7:56 Comment(1)
If the question was What is the easiest route from here?, this might be an answer. I find it not useful regarding django admin page login trouble.Millar

© 2022 - 2024 — McMap. All rights reserved.