All technological notes.
| Development | Deployment | Description |
|---|---|---|
STATIC_URL |
Static files url | |
STATICFILES_DIRS |
Global Static File Physical location | |
STATIC_ROOT |
Physical location for collectstatic |
Static Files
Django 处理静态文件有两种模式
Search Order
STATICFILES_DIRS, using the order you have provided.STATICFILES_DIRS > App Static Foldersettings.DEBUG = Truesettings.pyINSTALLED_APPS: includes django.contrib.staticfilesSTATIC_URL:STATIC_ROOT.# by default
STATIC_URL = "static/"
You're using the staticfiles app without having set the required STATIC_URL setting.STATICFILES_DIRS: global static files, if applied.Example:
from pathlib import Path
STATICFILES_DIRS = [
BASE_DIR / 'static',
BASE_DIR / 'collectstatic',
]
<!-- add at the top of html codes -->
<!-- load static -->
<!-- using static tag to referencing static files -->
<img src="static 'my_app/example.jpg'" alt="My image"> <!-- without {} % signs due to github deploy --->
<link rel="stylesheet" type="text/css" href="static '/Workout/carousel.css' " />
Store your static files in a folder called static in your app.
约定的文件夹结构 app static file
<app_name>/
static/
<app_name>/: by putting static files inside another directory named for the application itself, namespace issue can be prevented.
INSTALLED_APPS does not have django.contrib.staticfiles, django.views.static.serve() can serve static files manually.from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
settings.py
DEBUG = Falsesettings.pySTATIC_ROOT
Example:
STATIC_ROOT = "/var/www/example.com/static/"
STATIC_ROOT = BASE_DIR / 'collect_static/'
collectstaticcollectstatic management commandThis will copy all files from your static folders into the STATIC_ROOT directory.
$ cd <django_project>
$ python manage.py collectstatic
STATIC_ROOT参数指定的文件夹创建设置文件:<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<!-- 覆盖FastCGI handler,让IIS访问静态文件 -->
<handlers>
<clear/>
<add name="StaticFile"
path="*"
verb="*"
modules="StaticFileModule"
resourceType="File"
requireAccess="Read" />
</handlers>
</system.webServer>
</configuration>
代码说明:
- 如果没有该代码,当浏览器打开 static_root 地址时会返回 url 错误的信息;当存在该代码时,会返回 404 的服务器代码,即将 static_root 的访问的路由错误变为服务器的权限错误。


