django 模板使用静态文件

1、新建项目

2、新建app,并在install_app中添加该app

3、和app文件夹并列新建static、和TEMPLATES  文件夹,分别放静态文件和模板

4、setting.py中设置

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, "templates").replace("\\", "/")
        ],
        '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',
            ],
        },
    },
]

 

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static").replace("\\","/"),
)

 

5、修改模板文件

顶部添加  

{% load staticfiles %}

替换相关文件:
<link rel="stylesheet" type="text/css" href="lib/bootstrap/css/bootstrap.css">
替换成:

<link rel="stylesheet" type="text/css" href="{% static 'lib/bootstrap/css/bootstrap.css' %}">


另外一种配置静态文件url.py
import os.path
from django.conf.urls.defaults import *
from bookmarks.views import *
site_media = os.path.join(
  os.path.dirname(__file__), 'static'
)
urlpatterns = patterns('',
  (r'^$', main_page),
  (r'^user/(\w+)/$', user_page),
  (r'^login/$', 'django.contrib.auth.views.login'),
  (r'^logout/$', logout_page),
  (r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
  { 'document_root': site_media }),
)

 

posted @ 2017-09-05 21:36  testway  阅读(634)  评论(0编辑  收藏  举报