Why app/admin in debug mode false give me Server Error 500
Asked Answered
C

4

7

I changed my server settings.py from Debug = True to Debug = False.

I can get httpResponses from my other app urls but I can't access the /admin url specifically, I get the Server Error (500)

I tried to change the ALLOWED_HOSTS = ['my-app-name.herokuapp.com','*'] as other topics of this problem says but it didn't help me in my case.

(added '*' just for this question and to show that I tried it and it doesn't solve the problem)


EDIT 1(Settings added):

settings.py

"""
Django settings for mysite project.

Generated by 'django-admin startproject' using Django 1.10.3.

For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""

import os
import dj_database_url


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

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

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

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

ADMINS = [('admin', '[email protected]')]
MANAGERS = ADMINS
ALLOWED_HOSTS = ['mysitename.herokuapp.com', 'localhost', '127.0.0.1','*']


# Application definition

INSTALLED_APPS = [
    'Myappname.apps.MyAppNameConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'whitenoise.runserver_nostatic',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    'django.contrib.admindocs',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'Mysiteproj.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'Mysiteproj.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
# Update database configuration with $DATABASE_URL.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'

# Extra places for collectstatic to find static files.
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/

STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'

# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True

# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

EDIT 2 (Log added):

I had problem with creating a log file. now that I manage to config it, here is the log trace when I try to access admin site.

Internal Server Error: /admin/login/
Traceback (most recent call last):
  File "c:\Python27\lib\site-packages\django\core\handlers\exception.py", line 39, in inner
    response = get_response(request)
  File "c:\Python27\lib\site-packages\django\core\handlers\base.py", line 217, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "c:\Python27\lib\site-packages\django\core\handlers\base.py", line 215, in _get_response
    response = response.render()
  File "c:\Python27\lib\site-packages\django\template\response.py", line 109, in render
    self.content = self.rendered_content
  File "c:\Python27\lib\site-packages\django\template\response.py", line 86, in rendered_content
    content = template.render(context, self._request)
  File "c:\Python27\lib\site-packages\django\template\backends\django.py", line 66, in render
    return self.template.render(context)
  File "c:\Python27\lib\site-packages\django\template\base.py", line 208, in render
    return self._render(context)
  File "c:\Python27\lib\site-packages\django\template\base.py", line 199, in _render
    return self.nodelist.render(context)
  File "c:\Python27\lib\site-packages\django\template\base.py", line 994, in render
    bit = node.render_annotated(context)
  File "c:\Python27\lib\site-packages\django\template\base.py", line 961, in render_annotated
    return self.render(context)
  File "c:\Python27\lib\site-packages\django\template\loader_tags.py", line 174, in render
    return compiled_parent._render(context)
  File "c:\Python27\lib\site-packages\django\template\base.py", line 199, in _render
    return self.nodelist.render(context)
  File "c:\Python27\lib\site-packages\django\template\base.py", line 994, in render
    bit = node.render_annotated(context)
  File "c:\Python27\lib\site-packages\django\template\base.py", line 961, in render_annotated
    return self.render(context)
  File "c:\Python27\lib\site-packages\django\template\loader_tags.py", line 174, in render
    return compiled_parent._render(context)
  File "c:\Python27\lib\site-packages\django\template\base.py", line 199, in _render
    return self.nodelist.render(context)
  File "c:\Python27\lib\site-packages\django\template\base.py", line 994, in render
    bit = node.render_annotated(context)
  File "c:\Python27\lib\site-packages\django\template\base.py", line 961, in render_annotated
    return self.render(context)
  File "c:\Python27\lib\site-packages\django\template\loader_tags.py", line 70, in render
    result = block.nodelist.render(context)
  File "c:\Python27\lib\site-packages\django\template\base.py", line 994, in render
    bit = node.render_annotated(context)
  File "c:\Python27\lib\site-packages\django\template\base.py", line 961, in render_annotated
    return self.render(context)
  File "c:\Python27\lib\site-packages\django\templatetags\static.py", line 104, in render
    url = self.url(context)
  File "c:\Python27\lib\site-packages\django\templatetags\static.py", line 101, in url
    return self.handle_simple(path)
  File "c:\Python27\lib\site-packages\django\templatetags\static.py", line 114, in handle_simple
    return staticfiles_storage.url(path)
  File "c:\Python27\lib\site-packages\django\contrib\staticfiles\storage.py", line 132, in url
    hashed_name = self.stored_name(clean_name)
  File "c:\Python27\lib\site-packages\django\contrib\staticfiles\storage.py", line 292, in stored_name
    cache_name = self.clean_name(self.hashed_name(name))
  File "c:\Python27\lib\site-packages\django\contrib\staticfiles\storage.py", line 95, in hashed_name
    (clean_name, self))
ValueError: The file 'admin/css/base.css' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object at 0x0465BAF0>.
"GET /admin/login/?next=/admin/ HTTP/1.1" 500 27

Why does it block me? How can I fix it? thanks.

Corncob answered 17/12, 2016 at 15:58 Comment(7)
Try ALLOWED_HOSTS = ['*']Pauwles
I already tried this locally and remotely, didn't work for me.Corncob
If you can access other URLs, except for /admin, I suppose Django handles error by itself. If so, you can override handler500 and create a custom view to understand the nature of an error: docs.djangoproject.com/en/1.10/topics/http/views/…Leghorn
Try to read app logs.Barris
Whenever there's an internal server error with DEBUG=False, Django emails the administrator. You need to configure Django to send such emails.Seventeen
Just to make sure, if you change DEBUG to True, does /admin work? (BTW, don't call /admin a domain it's a URL; a domain is another thing.)Seventeen
@AntonisChristofides yes, it work fine in debug mode true.Corncob
T
10

While i was looking at your logs I came with a suggestion that might be your problem.

When loading admin pages Django uses it's own static files in order to show you with proper HTML/JS/CSS the website you see as the administration pages for your models.

All of these files come from the Django library. When you are saying that you aren't debugging your server(DEBUG=FALSE), Django wants to load all the assets(HTML,JS,CSS files) the running enviornment of the project and not the library itself.He does that because he is depending on the developer to call the collectstatic command which needs a proper & working static files configuration.


By the way, when i say proper configuration i mean directories and paths that exists.


More over , if you have a wrong configuration for loading static files(files like jQuery,Bootstrap & etc...) you can't load them...

I see by the configuration and other comments that you are using Heroku. Heroku by default automaticlly calls the collectstatic command for you when he needs of course to collect all the static files(Including the ADMIN files....) Link for ref - Heroku - Django and Static Assets

So we know so far few things:

  • Static files configuration needed not only for our files but also for admin pages
  • When you build Django application on Heroku you execute collectstatic automaticlly but it will not work quite right if the configuration is not valid.
  • On the log you posted as I see you can't reach the css file of the admin pages so it's a red light for what i am describing..

I have a huge guess that your static files configuration is wrong and you never called or checked the collectstatic command locally on your machine. Which means you are developing a REST api server with access to admin pages to monitor your database... when you are using Django in this manner and not for developing websites, that usualy happens.

I am not implying that it's wrong to develop REST api with Django or anything I am just trying to make everything clear

Try using this code snippet for your static files configuraiton:

PROJECT_ROOT = os.path.dirname(os.path.abspath(_file_))

STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')
STATIC_URL = '/static/'

# Extra places for collectstatic to find static files.
STATICFILES_DIRS = (
    os.path.join(PROJECT_ROOT, 'static'),
)

I hope this answer will work for you and please do tell if it did.

Tasman answered 24/12, 2016 at 18:14 Comment(0)
J
1

Specify the ADMINS setting so that you will receive emails on 500 errors in production mode:

ADMINS = (
    ('Your name', '[email protected]'),
)

Documentation: https://docs.djangoproject.com/en/1.10/ref/settings/#admins Also make sure that EMAIL_HOST, EMAIL_HOST_USER and EMAIL_HOST_PASSWORD are set.

You should also see the real error in your application log on Heroku.

Jordison answered 21/12, 2016 at 15:8 Comment(1)
I tried to configure a gmail smtp settings, I couldn't get it right, I didn't get any mail and try different settings also on my gmail account, didn't work.Corncob
V
1

This issue appears to be related to the access of static assets.

It seems like a similar issue was posted: Django staticfiles not found on Heroku (with whitenoise)

This issue seems to be resolved by changing a configuration for static assets.

Vitascope answered 23/12, 2016 at 3:14 Comment(3)
Hi, first of all, thanks. I managed to figure out that my path wasn't set right and i couldn't use python manage.py collectstatic till it was. Now the problem is using that command on heroku.Corncob
I'm not very familiar with Heroku, but it sounds like you can set it to run in your Procfile. This is from vpoulain's response in the thread posted above.Vitascope
@LamaTo, Heroku should run collectstatic automatically. Please edit your question and add the output from a git push to Heroku.Tintoretto
O
0

Also got this problem, but solution lied in nginx configuration from static location. Should be

location /static/ {
    root /var/www/fancy-project/;
}

instead of

location /static/ {
    root /var/www/fancy-project/static/;
}

Maybe this will be useful for someone

Oldtime answered 11/3, 2018 at 23:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.