简体   繁体   English

Django 管理员每次点击后都要求登录

[英]Django admin asks for login after every click

I'm working on a Django app hosted on Heroku.我正在开发 Heroku 上托管的 Django 应用程序。 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.但是在每次单击(或几秒钟后的每次单击)时,它都会再次将我重定向到登录页面,并将?next=/admin/model添加到 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 .我尝试了这里提到的建议: 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:这是我的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

In my case, this happened because I was running another Django development server at the same time (same domain, different port).就我而言,这是因为我同时运行另一个 Django 开发服务器(相同域,不同端口)。 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.如果您错过了问题中链接的文档:如果您需要运行多个 django 服务器,您可以通过为每个服务器设置不同的SESSION_COOKIE_NAME来解决此问题。

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.万一其他人发生这种情况,我遇到了完全相同的问题,并最终意识到如果密钥尚未设置为环境变量,我会在我的settings.py文件中随机生成SECRET_KEY值。 I had completely forgotten to set this on Heroku, after which the issue was resolved.我完全忘记在 Heroku 上设置它,之后问题就解决了。

'django.contrib.auth.middleware.SessionAuthenticationMiddleware', '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] https://docs.djangoproject.com/en/1.8/ref/middleware/#django.contrib.auth.middleware.SessionAuthenticationMiddleware]

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.我的 Django & React 项目遇到了同样的问题,问题是我在应用程序的主页上无条件调用了经过身份验证的所需端点。

I fixed the problem by providing needed headers at my frontend (React).我通过在我的前端 (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 应用程序就是这样,我确实访问了端点,而不关心用户是否经过身份验证。

    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.如果用户通过身份验证,我提供了点击此端点,如果用户通过身份验证,我提供了一个正确的令牌来点击这个 URL。

Note: I store my token inside of my localStorage .注意:我将令牌存储在localStorage

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM