【问题标题】:Django static files are not loadingDjango 静态文件未加载
【发布时间】:2016-11-06 22:02:10
【问题描述】:

我正在尝试将我的静态文件(css、js 等)导入我的 django 项目。但无论我尝试什么,它都会显示错误 500。 我已经在这里阅读了官方文档https://docs.djangoproject.com/en/1.9/howto/static-files/,但我只是看不到问题:/。 困扰我的是模板导入似乎起作用了。

我在开发控制台中看到的 GET 请求似乎也是合法的,例如:"http://127.0.0.1:8000/static/css/custom.css" 其中 custom.css 在 /project_folder/static/css/custom.css 中。

我的文件夹结构:

myproject
-> static
-->css
--->custom.css
-> templates
-->base.html(where i request the static file)
-> myproject(app)
-->settings.oy
-->urls.py
-> data_handler(app)
-->static

..

这是我的 settings.py:

"""
Django settings for myproject project.

Generated by 'django-admin startproject' using Django 1.9.7.

For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""

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/1.9/howto/deployment/checklist/

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

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'rest_framework',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myproject',
    'info_pages',
    'data_handler',
]

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'myproject.urls'

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


# Database
# https://docs.djangoproject.com/en/1.9/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/1.9/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/1.9/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/1.9/howto/static-files/


STATICFILES_DIRS = ( 
    os.path.join(BASE_DIR,'static/'),
    os.path.join(BASE_DIR,'data_handler/static/'),
    os.path.join(BASE_DIR,'myproject/static/'),
    )

STATIC_URL = '/static/'
STATIC_ROOT= os.path.join(BASE_DIR,'static/')

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

我导入静态文件的base.html:

{% load staticfiles %}
<!DOCTYPE html>

<head>
  <meta name="generator" content=
  "HTML Tidy for HTML5 (experimental) for Mac OS X https://github.com/w3c/tidy-html5/tree/c63cc39">
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>SMGR: Slime Mold Graph Repository</title>
  <link href="{% static "css/bootstrap.min.css" %}" rel="stylesheet">
  <link href="{% static "css/sticky_footer.css" %}" rel="stylesheet">
  <link href="{% static "css/custom.css" %}" rel="stylesheet">
  <link href="{% static "css/expandy.css" %}" rel="stylesheet">
  <link rel="shortcut icon" type="image/png" href="{% static "favicon/favicon.ico" %}"/>
  <script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
</head>

<body>
    {% block content %}
    {% endblock content %}
<div class="spacer-huge"/>
</body>

<footer class="footer" style="left:0px;">
  <div class="container" style="margin-top:9px">
    <a href="http://www.mpi-inf.mpg.de/departments/algorithms-complexity/">
      <img src="{% static "images/mpilogo-inf-wide.png" %}" alt="mpi logo"></a>
    <div style="float:right">
      <p class="small">
        <a href="http://www.mpi-inf.mpg.de/imprint/" style="font-size:large;">Imprint</a>
      </p>
    </div>
  </div>
</footer>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script> <!-- Include all compiled plugins (below), or include individual files as needed -->
   <script src="{% static "js/bootstrap.min.js" %}">
</script>

【问题讨论】:

  • 您还需要在根 urls.py 中添加 url。检查这个docs.djangoproject.com/en/1.9/howto/static-files/…
  • @RajeshYogeshwar 是对的,只是一个小细节,如果你在 DEBUG = True 中,你需要这样做,这是你的情况。这是生产中的另一种方式
  • 谢谢!我更改了我的 settings.py,所以我对我的 staticfiles_dirs 进行了硬编码,所以我不必在 urls.py 中付出任何额外的努力。

标签: django


【解决方案1】:

使用 django 1.9 你有两种方法可以做到这一点。 当您处于 DEBUG=True 时,它​​是您的 runserver 模拟服务器,但您需要为您的静态提供服务。 所以你可以这样做:

  • 在您的应用中使用 django.contrib.staticfiles,并设置好的静态 dir 和 url(在列表中)。
  • 在您的根 url 文件中提供它们,就像

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

当您的项目将由真实服务器提供服务时,您需要执行this

【讨论】:

    猜你喜欢
    • 2019-08-31
    • 2014-11-12
    • 2021-04-03
    • 2012-01-21
    • 1970-01-01
    • 2015-05-11
    • 2020-08-31
    • 2012-09-03
    相关资源
    最近更新 更多