Как отформатировать страницу администрирования Django / Heroku - PullRequest
0 голосов
/ 17 апреля 2020

Я перепробовал все решения в других вопросах, и, похоже, ничего не работает.

Я создал веб-приложение, используя Django, и развернул его с помощью Heroku, который работает.

Единственная проблема - это форматирование моей страницы администратора живого сайта, которая отформатирована не так хорошо, как все остальные страницы. Тем не менее, он отлично отформатирован, когда я поднимаю сайт на моем локальном хосте. Я проверил свой код в Settings.py, и у меня установлена ​​папка stati c с файлом placeholder.txt. У меня все мой код settings.py правильный, я чувствую.

Я запустил

heroku run python manage.py collectstatic

, что выполнялось нормально, хотя, когда я локально запустил

python manage.py collectstatic

, я получил ошибку, сказав:

django.core.exception.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a file system path
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '((___*)b^_@_+_!'  #left out key

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True       # Changed from False to True on pg. 477

ALLOWED_HOSTS = ['localhost', '127.0.0.1']   # Changed from [] to ['localhost'] on pg. 477

# Application definition

INSTALLED_APPS = [          #This is a tuple telling Django which apps work together to make up
    'django.contrib.admin', #the project. Add our app to this tuple by modifying INSTALLED_APPSS.
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # Third party apps
    'bootstrap3',        # Bootstrap is basically a large collection of styling tools.
                        # and has a number of "canned" style templates to use.
    #My apps added
    'learning_logs',
    'users',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    '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 = 'learning_log.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'learning_log/templates')],
        '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 = 'learning_log.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.0/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',
    },
]


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

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

STATIC_URL = '/static/'

# My settings
LOGOUT_REDIRECT_URL = '/'   # This was an update see:  https://ehmatthes.github.io/pcc/chapter_19/README.html
# p. 442-443, The logout_view() View Function
# In Django 2.1 there is no need for a logout view, so ignore what you see in
# this section in the book. Instead, we’ll use a setting called LOGOUT_REDIRECT_URL in settings.py.
# It doesn’t really matter where this setting goes, but I like to put it in a section at the end
# of the file labeled # My settings:
LOGIN_URL = '/users/login/'

# Settings for django-bootstrap3
BOOTSTRAP3 = {
    'include_jquery': True, # we need django-bootstrap3 to include jQuery, a Javascript libary that
    }                       # enables some of the interactive elements that the Bootstrap template provides.

# Heroku Settings
cwd = os.getcwd()       # use getcwd( ) function which get the "current working directory" that the file is running from.
if cwd == '/app' or cwd[:4] == '/tmp':  # In a Heroku web app deployment, the directory is always /app
    import dj_database_url              # During the build process, the project runs from a temporary directory that starts with /tmp
    DATABASES = {           # Import dj_database_url to help configure the database on Heroku.
        'default': dj_database_url.config(default='postgres://localhost')    # Heroku uses PostgresSQL (also called
    }                                                       # Postgres), a more advanced database than SQLite
    # Honor the 'X-Forwarded-Proto' header for request.is_secure().
    SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')   #Support HTTPS requests

    # Allow only Heroku to host the project.
    ALLOWED_HOSTS = ['kane-learning-logs.herokuapp.com']
    # Ensure that Django will serve the project from Heroku's URL
    # Don't enable your project error messages from Django on the live server!
    DEBUG = False   # make sure this is False and not true! So Django won't share sensitive info when an error occurs

    # Static asset configuration    # Set up the project to serve static files correctly to Heroku
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    STATIC_ROOT = 'staticfiles'
    STATICFILES_DIRS = (
        os.path.join(BASE_DIR, 'static'),
    )
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...