7

I'm working on a Django app hosted on Heroku. I'm able to login to the admin with my username, password. But on every single click (or on each click after a few seconds) it redirects me to the login page again with the ?next=/admin/model added to the url. Infact sometimes it asks for login multiple times before it lets me view the admin console. This behaviour is not reflected in local deployment. Admin works just fine locally.

I tried the suggestion mentioned here:https://docs.djangoproject.com/en/1.8/faq/admin/#i-can-t-log-in-when-i-enter-a-valid-username-and-password-it-just-brings-up-the-login-page-again-with-no-error-messages. But that does not help.

Any clue what I could be doing wrong?

Here is my settings.py:

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'haystack',
    'hash',
    'smuggler',


)



MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
)

ROOT_URLCONF = 'ssite.urls'

WSGI_APPLICATION = 'ssite.wsgi.application'

SESSION_ENGINE = "django.contrib.sessions.backends.cache" 

TEMPLATE_CONTEXT_PROCESSORS = ('django.contrib.auth.context_processors.auth',
                               'django.core.context_processors.debug',
                               'django.core.context_processors.i18n',
                               'django.core.context_processors.media',
                               'django.core.context_processors.static',
                               'django.core.context_processors.tz',
                               'django.contrib.messages.context_processors.messages',
                               'django.contrib.auth.context_processors.auth',

AUTHENTICATION_BACKENDS = (
                           'django.contrib.auth.backends.ModelBackend',
                           )

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'hash',
        'USER': 'dc',
        'PASSWORD': 'dc',
        'HOST': '127.0.0.1',
        'PORT': '5432',

    }
}

LANGUAGE_CODE = 'en-us'

TIME_ZONE =  'Asia/Kolkata'

USE_I18N = True

USE_L10N = True

USE_TZ = True

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


BASE_DIR = os.path.dirname(os.path.abspath(__file__))

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

MEDIA_URL = '/media/'


HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
        'URL': 'http://127.0.0.1:9200/',
        'INDEX_NAME': 'haystack',
    },
}


# Parse database configuration from $DATABASE_URL
import dj_database_url
DATABASES['default'] =  dj_database_url.config()

# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

# Allow all host headers
ALLOWED_HOSTS = ['*']

# Static asset configuration
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'static'
STATIC_URL = '/static/'
#STATIC_ROOT = os.path.join(BASE_DIR, 'static')

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'


FIXTURE_DIRS = (
   os.path.join(BASE_DIR, 'fixtures'),
)

from urlparse import urlparse

es = urlparse(os.environ.get('SEARCHBOX_URL') or 'http://127.0.0.1:9200/')

port = es.port or 80

HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
        'URL': es.scheme + '://' + es.hostname + ':' + str(port),
        'INDEX_NAME': 'documents',
    },
}

if es.username:
    HAYSTACK_CONNECTIONS['default']['KWARGS'] = {"http_auth": es.username + ':' + es.password}


try:
    from local_settings import *
except ImportError as e:
    pass
8
  • Are there any errors in the developer console in your browser (F12)? Commented Aug 24, 2015 at 7:27
  • @Leistungsabfall: No, there are no errors.
    – Deepti
    Commented Aug 24, 2015 at 7:28
  • First : require login admin After admin login, so admin login is last call
    – dsgdfg
    Commented Aug 24, 2015 at 7:33
  • @SDilmac: I didn't understand what you're saying fully. I'm not asking for login with "require login admin" at any point if that is what you're talking about.
    – Deepti
    Commented Aug 24, 2015 at 7:36
  • 1
    What does you INSTALLED_APPS look like? do you have django.contrib.sessions? Check each thing in the list at the top of this page: docs.djangoproject.com/en/1.8/ref/contrib/admin Commented Aug 24, 2015 at 7:48

4 Answers 4

7

In my case, this happened because I was running another Django development server at the same time (same domain, different port). I don't know the details of what caused this issue, but shutting down the other server fixed the problem.

EDIT
In case you missed the docs linked to in the question: if you need to run multiple django servers, you may be able to resolve this issue by setting a different SESSION_COOKIE_NAME for each.

4
  • Well, yes. I need to run both projects simultaneously for testing though, have you figured out anything else about this? Commented Mar 3, 2017 at 12:51
  • 1
    @guival this is probably what you are looking for: stackoverflow.com/questions/7433380/… Commented Mar 3, 2017 at 19:24
  • it certainly pointed me in the right directions thanks :) Knowing its something being saved in the session I'm just using two different sessions instead of messing with cookies and whatnot. Commented Mar 6, 2017 at 9:18
  • also consider changing SESSION_COOKIE_PATH setting, docs say: «This is useful if you have multiple Django instances running under the same hostname. They can use different cookie paths, and each instance will only see its own session cookie.»
    – nad_rom
    Commented Sep 18, 2020 at 22:01
6

In case this happens to anyone else, I had the exact same issue and eventually realised that I was randomly generating the SECRET_KEY value in my settings.py file if the key wasn't already set as an environment variable. I had completely forgotten to set this on Heroku, after which the issue was resolved.

1
  • I'd fallen into same trap - although settings.py was looking up SECRET_KEY from environment variables, I hadn't set that in Heroku dashboard! Logged in user could do some tasks in my app, others required random login. Setting the config var in Heroku resolved the issue. Commented Jan 15 at 11:30
0

'django.contrib.auth.middleware.SessionAuthenticationMiddleware',

I think this will do the trick. https://docs.djangoproject.com/en/1.8/ref/middleware/#django.contrib.auth.middleware.SessionAuthenticationMiddleware]

1
  • That does not change anything. Also, the admin login is working fine on my local server. Running it on Heroku is causing the problems.
    – Deepti
    Commented Aug 24, 2015 at 8:43
0

I had the same issue with my Django & React project, the problem was that I was calling an authenticated needed endpoint at the home page of the app without any condition.

I fixed the problem by providing needed headers at my frontend (React).

My endpoint was like this:

 class CartView(APIView):
        serializer_class = CartSerializer
        permission_classes = [IsAuthenticated,]

        def get(self, request, format=None):
            user = request.user
            items = Cart.objects.filter(username=user, ordered=False)
            
            if items.exists():
                return Response(CartViewSerializer(items, many=True).data, status=status.HTTP_200_OK)
            return Response({'message' : 'No Items have been added'}, status=status.HTTP_204_NO_CONTENT) 

User should be authenticated to hit this endpoint and my React app was like this and I did hit the endpoint without caring whether user is authenticated or not.

    React.useEffect(() => {
          axios.get('/api/add-to-cart')
              .then(res => {
                dispatch(addToCartCount(res.data.length));
                dispatch(showCartItems(res.data));
        }, [])

So I changed it into this:

    React.useEffect(() => {
        if (props.isAuthenticated) {
          const token = localStorage.getItem('token')
          let config = {
            headers: {
              'Authorization': `Token ${token}`
            }
          }
          axios.get('/api/add-to-cart', config)
              .then(res => {
                dispatch(addToCartCount(res.data.length));
                dispatch(showCartItems(res.data));
              
              })
          }
        }, [])

I provided that hit this endpoint if user is authenticated and if user is authenticated I provided a proper token for hitting this URL.

Note: I store my token inside of my localStorage.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.