Django中主要的静态引用文件是static
中的Css
,JavaScript
文件,这些文件是templates
下的各个html
文件进行引用.然后是用户和管理员上传的图片视频等Media
文件,这些在实际页面中进行展示.
1.设置变量STSTIC_DIR和MEDIA_DIR,用于获取文件的路径.
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__)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
STATIC_DIR = os.path.join(BASE_DIR,'static') # 需要加入的STASTIC_DIR路径变量
MEDIA_DIR = os.path.join(BASE_DIR,'media') # 需要加入的MEDIA_DIR路径变量
2.加入变量STATICFILES_DIRS和MEDIA_ROOT
STATICFILES_DIRS = [STATIC_DIR,] #加入的变量STATICFILES_DIRS,注意这里是列表形式,可以写入多个
MEDIA_ROOT = MEDIA_DIR # 加入的变量MEDIA_ROOT,只可以写入一个
3.加入变量STATICFILES_URL和MEDIA_URL ,主要用于客户端可通过URL直接访问
STATIC_URL = '/static/' #此次加入的变量STATIC_URL
MEDIA_URL = '/media/' # 此次加入的变量MEDIA_URL
4.在settings.py文件中新加入:django.template.context_processors.media
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR,],
'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',
'django.template.context_processors.media', # 新加入的
],
},
},
]
5.在项目的urls.py文件中url映射列表后面加入 static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import include
from django.conf import settings # 新加入
from django.conf.urls.static import static # 新加入
from rango import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$',views.index, name='index'),
url(r'^rango/',include('rango.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # 新加入