开启代码之旅 Launch With Code


1344 浏览 6 years, 1 month

15 Load Static Files (CSS, JS, & Images) in Django

版权声明: 转载请注明出处 http://www.codingsoho.com/

静态文件处理

  • 定义文件路径
  • 在html文件中添加静态文件处理
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, 'static','media')

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "[http://example.com/media/](http://example.com/media/)", "[http://media.example.com/](http://media.example.com/)"
MEDIA_URL = '/media/'

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = os.path.join(BASE_DIR, 'static','static_root')

# URL prefix for static files.
# Example: "[http://example.com/static/](http://example.com/static/)", "[http://static.example.com/](http://static.example.com/)"
STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    os.path.join(BASE_DIR, 'static','static_dirs'),
)

base.html

{% load staticfiles %}
<link href = "{% static 'css/bootstrap.min.css' %}" rel = "stylesheet">
<link href = "{% static 'css/jumbotron.css' %}" rel = "stylesheet">
    <link href = "{% static 'js/bootstrap.min.css' %}" rel = "stylesheet">
    <div class="jumbotron">
      <div class="container">
        <div class="col-sm-6">
          <h1>Hello, world!</h1>
          <p>This is a template for a simple marketing or informational website. It includes a large callout called a jumbotron and three supporting pieces of content. Use it as a starting point to create something more unique.</p>
          <p><a class="btn btn-success btn-lg" href="#" role="button">Learn more &raquo;</a></p>
        </div>
        <div class="col-sm-6">
          <img src = "{% static 'img/iphone.png' %}" class = "img-responsive" />
        </div>
      </div>
    </div>