【问题标题】:django include static files in templates?django 在模板中包含静态文件?
【发布时间】:2015-11-19 10:59:57
【问题描述】:

伙计们,我是 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

【问题讨论】:

    标签: python django


    【解决方案1】:

    你说你有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/'

    【讨论】:

    • 它被删除了。粘贴..无论如何它现在可以通过将静态文件夹放在 manage.py 所在的位置..谢谢
    • @Sidharth,哦,好的,太好了!
    • 但 wt 是之前的问题。我在静态 url 中有“/hostel_management/static/”.. 和 hostel_management 文件夹中的静态文件夹.. 为什么它不工作呢? @pythad
    • @Sidharth STATIC_URL: '/static/' 通常很好,它只是静态文件的前缀。你必须在你的STATICFILES_DIRS 中写/hostel_management/static/os.path.join(BASE_DIR, "hotel_managment/static")
    【解决方案2】:

    加载静态文件的方式有误。以这种方式加载它:

    <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')
    

    如果您可以在项目中提供完整的文件夹结构,则可以告诉您确切的更改。

    【讨论】:

      【解决方案3】:

      将您的静态网址更改为

      STATIC_URL = '/static/'
      

      在您的模板中,将以下行放在开头

      {% load staticfiles %}
      

      对于整个项目所需的静态文件,您可以将它们放在与 manage.py 相同的目录中。对于绑定到特定应用程序的静态文件,您可以在 settings.py 中使用以下设置。就像你的情况

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

      )

      没有必要像你所做的那样在 urls.py 中包含 url。这不适合生产使用。 您也可以通过将模板目录移动到与静态文件目录相同的级别来尝试。

      【讨论】:

        【解决方案4】:

        将应用名称添加到已安装的应用[]

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

        【讨论】:

          猜你喜欢
          • 2023-03-29
          • 1970-01-01
          • 2016-04-13
          • 1970-01-01
          • 2013-04-12
          • 1970-01-01
          • 2015-09-15
          • 1970-01-01
          • 2013-06-18
          相关资源
          最近更新 更多