django 如何在模板中包含静态文件?

2 投票
5 回答
7033 浏览
提问于 2025-05-10 15:16

大家好,我是Django的新手。我在尝试把静态文件,比如图片和CSS,加载到我的模板里,但一直没成功。以下是我的代码:

-----------settings.py----------

"""

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

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

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

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '#####################################'

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

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
)

MIDDLEWARE_CLASSES = (
    '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',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'hostel_management.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['hostel_management/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 = 'hostel_management.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


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

STATIC_URL = 'hostel_management/static/'


STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
    '/var/www/static/',
)

---------urls.py---------

from django.conf.urls import include, url
from django.contrib import admin
from views import index

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^index/$', index)

]

------index.html------

{% load static from staticfiles %}
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script src="{% static "scripts.js" %></script>
     <img src="{% static "large-image.jpg" %}" alt="img" />

图片和JS文件都没有加载出来……

我的文件结构如下:

hostel_management
├── manage.py
├──hostel_management
|   ├──templates
├──static
|   ├──large_image.jpg
|   ├──script.js

相关文章:

  • 暂无相关问题
暂无标签

5 个回答

0

我也遇到了同样的问题。我发现包含的模板文件开头也需要加上代码 {% load static %},即使在上层模板里已经有了 {% load static %} 这段代码。

0

把应用程序的名称添加到 Installed Apps[]

    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'hello_world',#add here
)
0

把你的静态网址改成

STATIC_URL = '/static/'

在你的模板文件里,开头加上这一行

{% load staticfiles %}

对于整个项目都需要用到的静态文件,你可以把它们放在和 manage.py 文件同一个文件夹里。对于某个特定应用相关的静态文件,你可以在 settings.py 里使用以下设置。就像你这个情况

STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
'hostel_management/static/',

)

在 urls.py 里不需要像你那样包含网址,这样做不适合在生产环境中使用。你也可以试着把你的模板文件夹移动到和静态文件夹同一级别。

1

你在加载静态文件的方式上出错了。应该这样加载:

<link rel="stylesheet" href="{% static "script.js" %}">

我觉得你的settings.py文件里有问题。

你加载静态文件的方式是:

STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),"/var/www/static/',

这是根据Django文档的正确方式,

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

如果你能提供你项目的完整文件夹结构,那么我就能告诉你具体需要做哪些修改。

2

你说你有一个叫 script.js 的文件,但你却试图去获取一个叫 scripts.js 的文件。

{% load static %}
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script src="{% static 'script.js' %></script>
     <img src="{% static "large-image.jpg" %}" alt="img" />

另外,你需要把 static 文件夹移动到和 manage.py 文件同一个地方,并且设置 STATIC_URL = '/static/'

撰写回答