Django 服务器找不到静态文件

Django server can't find the static files

我们正在尝试设置 Django 服务器来托管使用 Bootstrap Studio 制作的 Web 应用程序。尝试合并后端代码和 Web 前端时,Django 无法找到静态 css 和 JS 文件(实际上存在)。

这是我们的目录树:

bookalobackend:
    -bookalo:
         +static
              -css
              -bootstrap
              -js
              -fonts
         +templates
    -bookalobackend (main project folder)

这是我们的 settings.py 文件:

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__)))
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

GEOIP_PATH = os.path.join(BASE_DIR, 'geoip2')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

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

ALLOWED_HOSTS = ['localhost']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'bookalo',
    'django.contrib.gis'
]

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 = 'bookalobackend.urls'

TEMPLATE_DIRS = (
    os.path.join(PROJECT_ROOT, 'templates').replace('\', '/'),
)

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 = 'bookalobackend.wsgi.application'

#STATIC_ROOT = os.path.join(BASE_DIR, "static/")

# Database
# https://docs.djangoproject.com/en/2.1/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/2.1/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/2.1/topics/i18n/

LANGUAGE_CODE = 'es-es'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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


STATIC_URL = '/static/'

这是我们的 .html 文件之一。我们只修改了 css 路径之一来测试所有内容,但它正在寻找必要的静态文件。

{% load static %}
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
    <title>Bookalo</title>
    <meta property="og:image" content="assets/img/icono.png">
    <meta name="description" content="Tu sitio web de compra y venta de material escolar de segunda mano. En Bookalo, puedes encontrar material de todas las etapas educativas, incluyendo infantil, primaria, ESO, bachillerato y universidad!">
    <meta property="og:type" content="website">
    <link rel="icon" type="image/png" sizes="401x401" href="assets/img/icono.png">
    <link rel="icon" type="image/png" sizes="401x401" href="assets/img/icono.png">
    <link rel="icon" type="image/png" sizes="401x401" href="assets/img/icono.png">
    <link rel="icon" type="image/png" sizes="401x401" href="assets/img/icono.png">
    <link rel="icon" type="image/png" sizes="401x401" href="assets/img/icono.png">
    <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}">
</head>

<body>
    <script src="assets/js/jquery.min.js"></script>
    <script src="assets/bootstrap/js/bootstrap.min.js"></script>
    <script src="assets/js/-Filterable-Cards-.js"></script>
    <script src="assets/js/Bold-BS4-Animated-Back-To-Top.js"></script>
    <script src="assets/js/Bootstrap-Tags-Input-1.js"></script>
    <script src="assets/js/Bootstrap-Tags-Input.js"></script>
    <script src="assets/js/Contact-FormModal-Contact-Form-with-Google-Map.js"></script>
    <script src="assets/js/favoritos.js"></script>
    <script src="assets/js/fileinput.js"></script>
    <script src="assets/js/fileinput.min.js"></script>
    <script src="assets/js/MUSA_carousel-extended.js"></script>
    <script src="assets/js/piexif.js"></script>
    <script src="assets/js/piexif.min.js"></script>
    <script src="assets/js/purify.js"></script>
    <script src="assets/js/purify.min.js"></script>
    <script src="assets/js/Sidebar-Menu.js"></script>
    <script src="assets/js/slider.js"></script>
    <script src="assets/js/sortable.js"></script>
    <script src="assets/js/sortable.min.js"></script>
    <script src="assets/js/starrating.js"></script>
</body>

</html>

我们是不是做错了什么,还是需要配置其他东西?

提前致谢!

如果您使用 django 作为 development server 那么,请在您的网址中添加以下代码:

from django.conf.urls.static import static
urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

然后您应该能够看到通过 django 提供的静态文件。但不建议将此设置用于生产服务器。

如果您在生产服务器中使用 NGINX 或 Apache,then you can use them to serve static contents as well. Alternatively, you can also use whitenoise 在生产中提供静态文件。

除了 ruddra 提到的将 dev-only 静态导入添加到您的 url 之外,请仔细检查您的文件结构。

Django documentation 建议命名空间静态和模板文件。您的文件结构应更改为以下内容:

bookalobackend:
    -bookalo:
         +static
              +bookalo
                   -css
                   -bootstrap
                   -js
                   -fonts
         +templates
              +bookalo
                   -your_template_files
    -bookalobackend (main project folder)

当然这需要更改视图中的模板:

render(request, 'bookalo/template_name.html, context=context)

以及将静态文件添加到模板的方式的变化:

{% load static %}
<link rel="stylesheet" href="{% static 'bookalo/bootstrap/css/bootstrap.min.css' %}">