78

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.

monkut
  • 42,176
  • 24
  • 124
  • 155
  • Can you paste your `urls.py` as well? – Pratik Mandrekar Aug 21 '12 at 09:27
  • 1
    Have you tried moving `django.middleware.csrf.CsrfViewMiddleware` before `django.contrib.auth.middleware.AuthenticationMiddleware` ? – Brandon Taylor Aug 21 '12 at 13:56
  • 1
    Does it work when you're running it from `./manage.py runserver` (*i.e.* not over `mod_wsgi`)? – supervacuo Aug 21 '12 at 19:23
  • 1
    Are you actually failing to authenticate? You could be 'logged in' but still looking at the login form. – John Mee Aug 21 '12 at 23:48
  • @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. – monkut Aug 22 '12 at 01:23
  • @Brandon I just tried putting csrf before auth and it still brings me back to the login screen. – monkut Aug 22 '12 at 01:26
  • 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. – Brandon Taylor Aug 22 '12 at 03:00
  • 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... – monkut Aug 22 '12 at 03:06
  • Does you user is_active? Also post console output, when you try to login – Sergey Lyapustin Aug 22 '12 at 14:03
  • 2
    @monkut could you try it without WSGI in the equation (see above)? – supervacuo Aug 22 '12 at 15:23
  • Agree with supervacuo, let's run it with the dev server to exclude wsgi, apache, ... as source of trouble – schacki Aug 22 '12 at 16:04
  • 3
    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. – Thomas Aug 22 '12 at 16:04
  • @supervacuo yes, I just confirmed that using runserver it does proceed pass the login screen. – monkut Aug 23 '12 at 00:56
  • Do apache error/access logs show anything? If it is a WSGI issue, there may be permission issues with some of your imports – RedBaron Aug 25 '12 at 05:53
  • You could at least show the mod_wsgi configuration to confirm you are doing the right thing there. – Graham Dumpleton Aug 27 '12 at 00:13
  • @RedBaron no unfortunately, there is nothing in the apache error log to point me anywhere. – monkut Aug 28 '12 at 00:53
  • @GrahamDumpleton thanks for mentioning that, I've added the apache config above. – monkut Aug 28 '12 at 01:49

26 Answers26

71

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

Francis Yaconiello
  • 10,829
  • 2
  • 35
  • 54
  • 1
    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. – monkut Aug 29 '12 at 01:28
  • 1
    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. – monkut Aug 29 '12 at 01:34
  • 21
    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. – Chris Johnson May 30 '14 at 02:52
  • 1
    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. – dhobbs Feb 20 '15 at 05:44
  • 1
    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. – monkut Nov 06 '15 at 06:31
  • 1
    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 ? – Ahtisham Dec 16 '17 at 14:44
  • What to do if a record is not being created in the django_session table? – leelum1 Jun 12 '18 at 12:24
  • Thx, checking session settings helped in my case :) – szaman Oct 12 '18 at 08:04
  • 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! – danidee Jul 09 '20 at 12:35
  • @danidee 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. – Francis Yaconiello Jul 26 '20 at 00:40
  • I tried with SESSION_COOKIE_SECURE = False. It is working fine with django==1.11.6 and python 3.5.2 – santhosh_dj Aug 06 '20 at 08:56
  • 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. – sshow Mar 01 '23 at 14:22
  • `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 admin – Pankaj Sajekar May 24 '23 at 09:21
22
>>> 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

Vishal Singh
  • 725
  • 7
  • 16
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
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.

Marquistador
  • 1,841
  • 19
  • 26
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

Suraj Kumar
  • 5,547
  • 8
  • 20
  • 42
  • 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? https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ – kyczawon May 28 '20 at 14:21
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/

Reimus Klinsman
  • 898
  • 2
  • 12
  • 23
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...

Lapin-Blanc
  • 1,945
  • 1
  • 17
  • 26
  • Thanks, I did try to create *another* superuser with this method and attempt to login, but I'm still having the same problem. – monkut Aug 29 '12 at 01:22
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.

Raj J
  • 326
  • 1
  • 5
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
frog32
  • 966
  • 7
  • 19
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.

pemistahl
  • 9,304
  • 8
  • 45
  • 75
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.

schacki
  • 9,401
  • 5
  • 29
  • 32
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.

Alexey Kachayev
  • 6,106
  • 27
  • 24
1

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

is_staff  => True  (if exit).
is_active  => True .
is_superuser => True.
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
1

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.

HudsonGraeme
  • 399
  • 3
  • 10
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'
Gaurav Jain
  • 1,549
  • 1
  • 22
  • 30
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.

Community
  • 1
  • 1
furins
  • 4,979
  • 1
  • 39
  • 57
0

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

systemctl restart nginx
lapin
  • 2,098
  • 2
  • 21
  • 30
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

Timothy Mugayi
  • 1,449
  • 17
  • 11
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.

kokociel
  • 497
  • 6
  • 17
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.

max
  • 9,708
  • 15
  • 89
  • 144
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.

GilbertS
  • 591
  • 8
  • 12
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.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
Haseeb
  • 2,039
  • 3
  • 11
  • 26
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):
yam
  • 1,383
  • 3
  • 15
  • 34
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.

101is5
  • 309
  • 2
  • 12
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'
Vova
  • 3,117
  • 2
  • 15
  • 23
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

-1

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

  • 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. – greybeard Dec 05 '19 at 08:18