首页 > 解决方案 > Django RestAPI 但没有 CSS

问题描述

我正在使用 Django Restframework 制作一个 REST API 它运行良好,但是当我将它推送到这样的铁路应用程序时出现错误

Installing SQLite3
-----> $ python manage.py collectstatic --noinput
       Traceback (most recent call last):
         File "/workspace/manage.py", line 22, in <module>
           main()
         File "/workspace/manage.py", line 18, in main
           execute_from_command_line(sys.argv)
         File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line
           utility.execute()
         File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute
           self.fetch_command(subcommand).run_from_argv(self.argv)
         File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv
           self.execute(*args, **cmd_options)
         File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute
           output = self.handle(*args, **options)
         File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle
           collected = self.collect()
         File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 114, in collect
           handler(path, prefixed_path, storage)
         File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 338, in copy_file
           if not self.delete_file(path, prefixed_path, source_storage):
         File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 248, in delete_file
           if self.storage.exists(prefixed_path):
         File "/app/.heroku/python/lib/python3.9/site-packages/django/core/files/storage.py", line 318, in exists
           return os.path.exists(self.path(name))
         File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/storage.py", line 38, in path
           raise ImproperlyConfigured("You're using the staticfiles app "
       django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path.

 !     Error while running '$ python manage.py collectstatic --noinput'.
       See traceback above for details.

       You may need to update application code to resolve this error.
       Or, you can disable collectstatic for this application:

          $ heroku config:set DISABLE_COLLECTSTATIC=1

       https://devcenter.heroku.com/articles/django-assets
ERROR: failed to build: exit status 1
ERROR: failed to build: executing lifecycle: failed with status code: 145

这是settings.py文件

"""

    Django settings for crm_project project.
    
    Generated by 'django-admin startproject' using Django 3.2.5.
    
    For more information on this file, see
    https://docs.djangoproject.com/en/3.2/topics/settings/
    
    For the full list of settings and their values, see
    https://docs.djangoproject.com/en/3.2/ref/settings/
    """
    
    from pathlib import Path
    import os
    from dotenv import load_dotenv
    load_dotenv()
    
    # Build paths inside the project like this: BASE_DIR / 'subdir'.
    BASE_DIR = Path(__file__).resolve().parent.parent
    
    
    # Quick-start development settings - unsuitable for production
    # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
    
    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = os.getenv('SECRET_KEY')
    
    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = os.getenv('DEBUG')
    
    ALLOWED_HOSTS = [
        'boss-instrument-production.up.railway.app', '127.0.0.1']
    
    
    # Application definition
    
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'rest_framework',  # new
        'customer',  # new
    ]
    
    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 = 'crm_project.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 = 'crm_project.wsgi.application'
    
    
    # Database
    # https://docs.djangoproject.com/en/3.2/ref/settings/#databases
    
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'NAME': os.getenv('PGDATABASE'),
            'USER': os.getenv('PGUSER'),
            'PASSWORD': os.getenv('PGPASSWORD'),
            'HOST': os.getenv('PGHOST'),
            'PORT': os.getenv('PGPORT'),
        }
    }
    
    
    # Password validation
    # https://docs.djangoproject.com/en/3.2/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.2/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.2/howto/static-files/
    
    STATIC_URL = '/static/'
    
    # Default primary key field type
    # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
    
    DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

我尝试通过添加DISABLE_COLLECTSTATIC具有 1 作为值的变量作为 env 变量之一来解决它。它可以工作,但是 API 页面中的 CSS 消失了

那么任何人都可以让我知道我可以做些什么来摆脱这个错误并将 CSS 放到网站上吗?

标签: pythoncssdjangoapistatic

解决方案


您应该利用WhiteNoise等工具来设置 Django 静态文件配置以进行生产。我认为您正在使用 Heroku,因此我只是在此处附加了一个settings.py适用于您的 Django 文件的示例配置。

PS:提醒你设置的时候Django不再处理你的静态文件了DEBUG=False

import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# and here the rest of your settings
# ...

# Static files configuration
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = os.path.join(BASE_DIR, 'static/')
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

# ...

# Loading test/prod settings based on ENV settings
ENV = os.environ.get('ENV')

# Add this part to the production environment only
# (Heroku in this case) with DEBUG=False:
try:
    from .production_settings import *
    MIDDLEWARE.append('whitenoise.middleware.WhiteNoiseMiddleware',)
except ImportError:
    pass

推荐阅读