【问题标题】:Django RestAPI but without CSSDjango Rest API 但没有 CSS
【发布时间】:2021-10-21 04:17:20
【问题描述】:

我正在使用 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'

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

那么谁能告诉我我可以做些什么来摆脱这个错误并将 CSS 放到网站上?

【问题讨论】:

标签: python css django api static


【解决方案1】:

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

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

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

【讨论】:

  • 我认为STATIC_URL 属性有误。您需要指定 URL 而不是路径。因此它需要类似于STATIC_URL = '/static/'。你可以看看这个帖子:stackoverflow.com/questions/37716200/…
  • 你提到的答案没有更新:STATIC_URL既可以是相对url也可以是绝对url,但是如何正确使用请参考Django官方文档docs.djangoproject.com/en/3.2/ref/settings/…
  • @Dos 请注意,当您使用os.path.join(BASE_DIR, 'static/') 时,由于该方法返回路径,因此静态文件是通过诸如https://example.com/var/www/my_project/static/ 之类的URL 提供的。
猜你喜欢
  • 2017-02-02
  • 2021-02-21
  • 2018-07-02
  • 1970-01-01
  • 1970-01-01
  • 2018-03-26
  • 2013-08-24
  • 2017-10-30
  • 2020-12-23
相关资源
最近更新 更多