简体   繁体   English

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

[英]django include static files in templates?

guys iam a newbee to django.. i was trying to load static files like images and css into my template.. but its not working.. here's the code伙计们,我是 django 的新手。

-----------settings.py---------- -----------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--------- ---------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------ ------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" />

neither the image nor the js file is loaded..既没有加载图像也没有加载 js 文件..

the filesystem is as follows文件系统如下

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

You say that you have script.js but you try to get scripts.js .你说你有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" />

Also you have to move static folder to the place where your manage.py is placed and set STATIC_URL = '/static/'此外,您必须将static文件夹移动到您的manage.py所在的位置并设置STATIC_URL = '/static/'

There is an error in the way you load the static files.加载静态文件的方式有误。 Load it this way:以这种方式加载它:

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

I think there is an error on you settings.py我认为你的 settings.py 有错误

where your way of loading static file is :您加载静态文件的方式是:

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

this is the way according to the django docs,这是根据django docs的方式,

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

if you can give a full folder structure in your project then telling you the exact changes will be possible.如果您可以在项目中提供完整的文件夹结构,则可以告诉您确切的更改。

Change your static url to将您的静态网址更改为

STATIC_URL = '/static/'

In your template, put following line in start在您的模板中,将以下行放在开头

{% load staticfiles %}

For static files which are required in your whole project, you can put them in same directory in which you have manage.py.对于整个项目中需要的静态文件,您可以将它们放在与 manage.py 相同的目录中。 For static files which are tied to a specific app, you can use following settings in your settings.py.对于绑定到特定应用程序的静态文件,您可以在 settings.py 中使用以下设置。 Like in your case就像你的情况

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

) )

There is no need to include url in urls.py as you have done.无需像您所做的那样在 urls.py 中包含 url。 This is not suitable for production use.这不适合生产使用。 You can also try it by moving your templates directory at same level as your static file directory.您也可以通过将模板目录移动到与静态文件目录相同的级别来尝试。

add app name into Installed Apps[]将应用名称添加到已安装的应用中[]

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM