【问题标题】:Django server can't find the static filesDjango 服务器找不到静态文件
【发布时间】:2019-08-29 11:27:38
【问题描述】:

我们正在尝试设置一个 django 服务器来托管使用 Bootstrap Studio 制作的网络应用程序。在尝试合并后端代码和 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>

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

提前致谢!

【问题讨论】:

  • 该文件的哪个 URL 保留在呈现的 html 中?手动打开此 URL 时出现什么错误状态?这会发生在 DEBUG=True 还是 False 中?你跑collectstatic了吗?

标签: django django-templates django-staticfiles django-settings


【解决方案1】:

如果您使用 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。或者,您也可以使用whitenoise 在生产环境中提供静态文件。

【讨论】:

    【解决方案2】:

    除了 ruddra 提到的将仅开发人员静态导入添加到您的 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' %}">
    

    【讨论】:

    • 非常感谢!但是由于只有一个应用程序,我们觉得在该级别使用静态,没有内部文件夹更适合链接。
    猜你喜欢
    • 1970-01-01
    • 2013-04-17
    • 2013-12-08
    • 2021-11-24
    • 2020-06-12
    • 2021-08-27
    • 2014-11-10
    • 2011-08-26
    • 2020-06-22
    相关资源
    最近更新 更多