【蘭山問(wèn)題】Django中的靜態(tài)文件

項(xiàng)目部署到阿里云(nginx+uwsgi)上后反镇,靜態(tài)文件加載沒(méi)有問(wèn)題奋蔚。但是在本地,使用開發(fā)服務(wù)器联贩,卻始終加載不成功漫仆。

settings\common.py:
STATIC_ROOT = os.path.join(BASE_DIR, 'xxx/yyy/static/')

#STATICFILES_FINDERS = (
#    'django.contrib.staticfiles.finders.FileSystemFinder',
#    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
#)

INSTALLED_APPS = [
    #'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sites',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    ...
]
STATICFILES_DIRS = [
#    os.path.join(BASE_DIR, 'xxx/yyy/static'),
]
STATIC_URL = '/static/'
settings\dev.py:
from .common import *
#是否注釋STATICFILES_FINDERS,對(duì)runserver --nostatic情況下泪幌,加載靜態(tài)文件沒(méi)有任何影響盲厌,都可以正常顯示署照;
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

#STATICFILES_FINDERS = (
#    'django.contrib.staticfiles.finders.FileSystemFinder',
#    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
#)
settings\prod.py:
from .common import *
from django.conf.urls.static import static
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    #Added at 20170428 開發(fā)環(huán)境下,如果注釋掉吗浩,無(wú)法正確加載靜態(tài)文件
    #urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

執(zhí)行python manage.py runserver

瀏覽器輸入http://127.0.0.1:8000/ 后建芙,可見(jiàn)各種靜態(tài)文件沒(méi)有正確加載。

Paste_Image.png

瀏覽器Dev模式下懂扼,顯示404錯(cuò)誤禁荸。
Paste_Image.png

瀏覽器輸入http://127.0.0.1:8000/static/site/v1/img/LOGO.PNG 后,顯示同樣的錯(cuò)誤404阀湿。
Paste_Image.png

執(zhí)行python manage.py runserver --nostatic

瀏覽器輸入http://127.0.0.1:8000/ 后赶熟,各種靜態(tài)文件正確加載。


Paste_Image.png
Paste_Image.png

瀏覽器輸入http://127.0.0.1:8000/static/site/v1/img/LOGO.PNG 后陷嘴,可以正確加載映砖。

靜態(tài)文件

生產(chǎn)環(huán)境

靜態(tài)文件交由Web Server處理,Django本身不處理靜態(tài)文件灾挨。簡(jiǎn)單的處理邏輯如下(以nginx為例):
URI請(qǐng)求 --->>> Web Server
按照Web Server里面的配置規(guī)則處理(以nginx為例邑退,主要配置在nginx.conf里面的location參數(shù)。)劳澄,如果是靜態(tài)文件地技,則由nginx直接處理;如果不是浴骂,則交由Django處理乓土,Django會(huì)根據(jù)urls.py里面的規(guī)則進(jìn)行匹配宪潮。

開發(fā)環(huán)境

以上是部署到Web服務(wù)器后的處理方式溯警,為了便于開發(fā),Django提供了在開發(fā)環(huán)境下對(duì)靜態(tài)文件的處理機(jī)制狡相,方法是這樣的(可能是低版本的步驟梯轻,僅供理解用,步驟謹(jǐn)慎懷疑):
1.在INSTALLED_APPS里面加入'django.contrib.staticfiles';
2.在urls.py里面加入:

if settings.DEBUG:  
   urlpatterns += patterns('', url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT }),   
        url(r'^static/(?P<path>.*)$','django.views.static.serve',{'document_root':settings.STATIC_ROOT}), )

3.這樣就可以在開發(fā)階段直接使用靜態(tài)文件了尽棕。

MEDIA_ROOT和MEDIA_URL

靜態(tài)文件的處理包括STATIC和MEDIA兩類喳挑,這往往容易混淆,在Django里面是這樣定義的:
MEDIA指用戶上傳的文件滔悉,比如在Model里面的FileField伊诵、ImageField上傳的文件。如果你定義MEDIA_ROOT=C:\temp\media回官,那么File = models.FileField(upload_to='abc/')曹宴,上傳的文件就會(huì)被保存到C:\temp\media\abc
舉個(gè)例子:

class blog(models.Model):  
       Title=models.charField(max_length=64)  
       Photo=models.ImageField(upload_to="photo")

上傳的圖片就是上傳到c:\temp\media\photo,而在模板中要顯示該文件歉提,則這樣寫{{MEDIA_URL}}blog.Photo笛坦。
在settings里面設(shè)置的MEDIA_ROOT必須是本地路徑的絕對(duì)路徑区转,一般是這樣寫,

PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))  
MEDIA_ROOT=os.path.join(PROJECT_PATH,'media/').replace('\\','/') 

MEDIA_URL 是指從瀏覽器訪問(wèn)時(shí)的地址前綴版扩,舉個(gè)例子:

MEDIA_ROOT=c:\temp\media\photo  
MEDIA_URL="/data/"                     #可以隨便設(shè)置  

在開發(fā)階段废离,media的處理由Django處理:訪問(wèn)http://localhost/data/abc/a.png 就是訪問(wèn) c:\temp\media\photo\abc\a.png,在模板里面這樣寫({{MEDIA_URL}}abc/a.png)礁芦,在部署階段最大的不同在于你必須讓web服務(wù)器來(lái)處理media文件蜻韭,因此你必須在web服務(wù)器中配置,以便能讓web服務(wù)器訪問(wèn)media文件柿扣。
以nginx為例湘捎,可以在nginx.conf里面這樣寫:

 location ~/media/{
   root   /temp/  
   break;
}

具體可以參考如何在nginx部署Django的資料。

STATIC_ROOT和STATIC_URL

STATIC主要指的是如css窄刘、js窥妇、images這樣的文件,在settings里面可以配置STATIC_ROOTSTATIC_URL配置方式與MEDIA_ROOT是一樣的娩践,但是要注意STATIC_ROOTMEDIA_ROOT位置不能一樣活翩。
STATIC文件一般保存在以下位置:

  1. STATIC_ROOT:在settings里面設(shè)置,一般用來(lái)放一些公共的js,css,image等翻伺。
  2. APP的static文件夾材泄,在每個(gè)APP所在文件夾中可以建立一個(gè)static文件夾,然后當(dāng)運(yùn)行collectstatic時(shí)吨岭,Django會(huì)遍歷INSTALL_APPS里面所有APP的static文件夾拉宗,將里面所有的文件復(fù)制到STATIC_ROOT。因?yàn)槔北瑁绻阋⒖蓮?fù)用的APP旦事,那么你要將該APP所需要的靜態(tài)文件放在static文件夾中。
    也就是說(shuō)一個(gè)項(xiàng)目引用了很多app急灭,那么這個(gè)項(xiàng)目所需要的css, images等靜態(tài)文件是分散在各個(gè)app的static文件的姐浮,比較典型的是admin應(yīng)用。當(dāng)你要發(fā)布時(shí)葬馋,需要將這些分散的static文件收集到一個(gè)地方就是STATIC_ROOT卖鲤。
  3. STATIC文件可以配置STATICFILES_DIRS,用以指定額外的靜態(tài)文件存儲(chǔ)位置畴嘶。
    STATIC_URL的含義與MEDIA_URL類似蛋逾。
    如果在部署階段找不到css,js,則可能是一下幾個(gè)問(wèn)題:
    1.web服務(wù)器配置有問(wèn)題窗悯,不同的部署方式對(duì)靜態(tài)文件的處理有所不同区匣;
    2.沒(méi)有運(yùn)行collectstatic將所需要的靜態(tài)文件收集到STATIC_ROOT

MEDIA_ROOT : 主要是為了存放上傳的文件蟀瞧,比如在ImageField中沉颂,這個(gè)值加上upload_to的值就是真實(shí)存放上傳圖片的文件位置条摸;
Django里,文件內(nèi)容實(shí)際上是不會(huì)存放到數(shù)據(jù)庫(kù)里邊的铸屉,大多數(shù)數(shù)據(jù)庫(kù)存放效率低钉蒲,需要保存在文件系統(tǒng)里。
MEDIA_URL : URL的映射彻坛,前后要加上"/"表示從根目錄開始顷啼,比如"/site_media/",加上這個(gè)屬性之后昌屉,靜態(tài)文件的鏈接前面會(huì)加上這個(gè)值钙蒙。
STATIC_ROOT :這個(gè)文件里面的目錄會(huì)當(dāng)成靜態(tài)文件處理。

STATIC_URL : URL映射间驮,指定靜態(tài)目錄的URL躬厌,默認(rèn)是"/static/"

STATICFILES_DIRS :指定一個(gè)工程里邊哪個(gè)目錄存放了與這個(gè)工程相關(guān)的靜態(tài)文件竞帽,是一個(gè)列表扔枫。如果列表中有一個(gè)是“/home/shishang/test/static”歹袁,其中有一個(gè)文件內(nèi)容是productlist.html铺然,我們只要訪問(wèn)http://localhost:8000/static/productlist.html就可以直接訪問(wèn)了撇吞。

Django提供了一個(gè)方法自動(dòng)地將所有的靜態(tài)文件放在一起。只要在寫App的時(shí)候創(chuàng)建一個(gè)static子目錄專門保存靜態(tài)文件就行了堆巧。在開發(fā)階段妄荔,不必費(fèi)心去做映射,不需要配置urls.py谍肤。在部署到生產(chǎn)環(huán)境的時(shí)候啦租,只需要配置Apache/static/映射到STATIC_ROOT,然后運(yùn)行manage.py collectstatic谣沸,自動(dòng)地STATICFILES_DIR列出的目錄以及各個(gè)APP下的static子目錄的所有文件復(fù)制到STATIC_ROOT刷钢。因?yàn)閺?fù)制過(guò)程可能會(huì)覆蓋掉原來(lái)的文件,所以乳附,一定不能把我們辛苦做出來(lái)靜態(tài)文件放這邊!在開發(fā)階段伴澄,Django把/static映射到django.contrib.staticfiles這個(gè)APP赋除。staticfiles自動(dòng)地從STATICFILES_DIRSSTATIC_ROOT以及各個(gè)App子目錄里面搜索靜態(tài)文件非凌。一旦部署到開發(fā)環(huán)境上举农,settings.py不需要重新編寫,只要在Apache的配置文件里面寫好映射敞嗡,/static將會(huì)被Apache處理颁糟。django.contrib.staticfiles雖然仍然存在航背,但因?yàn)椴粫?huì)接收到以/static/開始的路徑,所以將不會(huì)產(chǎn)生作用棱貌。不必?fù)?dān)心Django會(huì)使處理速度變慢玖媚。另外,當(dāng)settings.DEBUG is False的時(shí)候婚脱,staticfiles將自動(dòng)關(guān)閉今魔。

內(nèi)部是怎么工作的?

  1. 首先障贸,檢索settings.py中所有關(guān)于靜態(tài)文件的設(shè)置错森,它們是STATIC_URL,STATIC_ROOT, STATICFILES_FINDERS, STATICFILES_DIRS篮洁。
  2. 同樣我們已經(jīng)將'django.contrib.staticfiles'添加進(jìn)了INSTALLED_APPS涩维。
  3. 現(xiàn)在先不管STATIC_ROOTSTATICFILES_DIRS。即使你將它們注釋或者刪除袁波,你的項(xiàng)目依然能夠像想在一樣工作激挪。
  4. 我們需要將'django.contrib.statifiles'添加進(jìn)INSTALLED_APPS,如果我們想要使用Django默認(rèn)的靜態(tài)文件處理服務(wù)锋叨。
  5. 所謂Django默認(rèn)的靜態(tài)文件處理服務(wù)就相當(dāng)于需要使用Django提供的python manage.py runserver垄分。
  6. Django默認(rèn)在STATIC_URL下處理靜態(tài)文件。注意STATIC_URL已經(jīng)設(shè)置為‘/static/’娃磺。這就是為什么我們獲取到了我們的靜態(tài)文件薄湿,舉個(gè)例子,樣式文件在這個(gè)url下http://127.0.0.1:8000/static/style.css偷卧。
    如果你訪問(wèn) http://127.0.0.1:8000/static_changed/styles.css 豺瘤,你將會(huì)得到一個(gè)404頁(yè)面。如果你想要在 http://127.0.0.1:8000/static_changed/styles.css提供听诸, 需要設(shè)置 STATIC_URL = '/static_changed/'∽螅現(xiàn)在動(dòng)手試試吧。這只是為了舉例說(shuō)明STATIC_URL的用處晌梨,現(xiàn)在都改回默認(rèn)設(shè)置桥嗤,即 STATIC_URL = '/static/'
  7. 下一個(gè)問(wèn)題是仔蝌,Django是怎么知道從哪里去去讀取靜態(tài)文件的泛领,或者說(shuō)怎么知道去哪里找到靜態(tài)文件呢?這就是STATICFILES_FINDERS的作用了敛惊。
    STATICFILES_FINDERS中我們有兩條記錄:
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder

現(xiàn)在你可以先不管FileSystemFinder渊鞋,如果你愿意,你可以先注釋掉這一行。AppDirectoriesFinder告訴Django從INSTALLED_APPS中每一個(gè)app下的static/子目錄下去尋找靜態(tài)文件锡宋。記住儡湾,我們是將style.css放在了some_appstatic/子目錄下,這就是為什么Django能夠找到它执俩,并且進(jìn)行正確的處理徐钠。如果你將'/static/'子目錄修改為其它名字,你的靜態(tài)文件就不能被正確處理了奠滑。動(dòng)手試一試吧丹皱。注釋掉 AppDirectoriesFinder 這一行,然后訪問(wèn) http://127.0.0.1:8000/static/styles.css ,現(xiàn)在樣式文件不能被正確地處理了宋税。好摊崭,嘗試過(guò)后去掉注釋。
現(xiàn)在杰赛,我們知道了STATIC_URLSTATICFILES_FINDERS的作用呢簸。我們現(xiàn)在仍然不需要用到STATIC_ROOTSTATICFILES_DIRS

這里發(fā)生了什么乏屯?

  1. Django服務(wù)器收到一個(gè)關(guān)于靜態(tài)文件的請(qǐng)求根时,應(yīng)該是一個(gè)以'/static/'開頭的url。
  2. 它開始在STATICFILES_DIRS設(shè)定的所有目錄中尋找這個(gè)靜態(tài)文件辰晕,比如base.css蛤迎。
  3. 由于我們?cè)?code>STATICFILES_DIRS中指定了一個(gè)目錄,即project_static含友,Django服務(wù)器在這個(gè)目錄中嘗試尋找這個(gè)文件替裆。它在這個(gè)目錄中進(jìn)行搜索時(shí)找到了這個(gè)文件,然后進(jìn)行處理窘问。
  4. 如果沒(méi)有在STATICFILES_DIRS指定的目錄中找到這個(gè)文件辆童,它將會(huì)在INSTALLED_APPS下所有app的static/子目錄嘗試尋找。
    注意惠赫,這時(shí)候依然不需要添加staticfiles_urlpatterns()把鉴。

關(guān)于STATIC_ROOT

  1. 如果在開發(fā)階段使用Djangorunserver,你將永遠(yuǎn)不會(huì)需要STATIC_ROOT儿咱。
  2. 一旦你需要進(jìn)入生產(chǎn)庭砍,你能在服務(wù)器中使用它。Django提供了一個(gè)靜態(tài)文件管理的命令叫做collectstatic概疆,它將收集所有的靜態(tài)資源逗威,(如在STATICFILES_DIRS中找到的和在所有app下的static/子目錄中找到的靜態(tài)資源),將它們放進(jìn)一個(gè)STATIC_ROOT定義的位置岔冀。
    STATIC_ROOT只有你在使用collectstatic命令的時(shí)候才會(huì)有用處。

Refer to:

  1. http://blog.csdn.net/fighter_yy/article/details/41249033
  2. http://www.tuicool.com/articles/BjIBJi
  3. http://lanceverw.iteye.com/blog/1798037

settings

Django的STATICFILES_FINDERS設(shè)置項(xiàng)是一個(gè)列表,它包含了若干個(gè)知道如何從不同地點(diǎn)尋找靜態(tài)文件的搜尋器使套。其中之一是AppDirectoriesFinder罐呼,它會(huì)從INSTALLED_APPS中各個(gè)應(yīng)用的'static'子目錄中尋找文件。

STATICFILES_FINDERS

Default:
[
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]

The list of finder backends that know how to find static files in various locations.
The default will find files stored in the STATICFILES_DIRS setting(using django.contrib.staticfiles.finders.FileSystemFinder) and in a static subdirectory of each app(using django.contrib.staticfiles.finders.AppDirectoriesFinder). If multiple files with the same name are present, the first file that is found will be used.
One finder is disabled by default:
django.contrib.staticfiles.finders.DefaultStorageFinder. If added to your STATICFILES_FINDERS settings, it will look for static files in the default file storage as defined by the DEFAULT_FILE_STORAGE setting.
Refer: https://docs.djangoproject.com/en/1.11/ref/settings/

STATICFILES_STORAGE

Default: 'django.contrib.staticfiles.storage.StaticFilesStorage'
The file storage engine to use when collecting static files with the collectstatic management command.
A ready-to-use instance of the storage backend defined in this setting can be found at django.contrib.staticfiles.storage.staticfiles_storage.

The staticfiles app

django.contrib.staticfiles collects static files from each of your appliations(and any other places you specify) into a single location that can easily be served in production.
For an introduction to the static files app and some usage examples, seeManaging static files (e.g. images, JavaScript, CSS). For guidelines on deploying static files, see Deploying static files.

Management Commands

django.contrib.staticfiles exposes three management commands.

collectstatic

django-admin collectstatic
Collects the static files into STATIC_ROOT.
Duplicate files names are by default resolved in a similar way to how template resolution works: the file that is the first found in one of the speicified locations will be used. If you're confused, the findstatic command can help show you which files are found.
On subsequent collectstatic runs(if STATIC_ROOT isn't empty),files are copied only if they have a modified timestamp greater than the timestamp of the file in STATIC_ROOT. Therefore if you remove an application from INSTALLED_APPS, it's a good idea to use the collectstatic --clear option in order to remove stale static files.
Files are searched by using the enabled finders. The default is to look in all locations defined in STATICFILES_DIRS and in the 'static' directory of apps specified by the INSTALLED_APPS setting.
The collectstatic management command calls the post_process() method of the STATICFILES_STORAGE after each run and passes a list of paths that have been found by the management command. It also receives all command line options of collectstatic. This is used by the CachedStaticFileStorage by default.
For a full list of options, refer to the commands own help by running:

$python manage.py collectstatic --help

findstatic

django-admin findstatic staticfile [staticfile ...]

Searches for one or more relative paths with the enabled finders.
For example:

$ python manage.py findstatic css/base.css admin/js/core.js
Found 'css/base.css' here:
  /home/special.polls.com/core/static/css/base.css
  /home/polls.com/core/static/css/base.css
Found 'admin/js/core.js' here:
  /home/polls.com/src/django/contrib/admin/media/js/core.js

findstatic --first
By default, all matching locations are found. To only return the first match for each relative path, use the --first option:

$ python manage.py findstatic css/base.css --first
Found 'css/base.css' here:
  /home/special.polls.com/core/static/css/base.css

This is a debugging aid; it’ll show you exactly which static file will be collected for a given path.
By setting the --verbosity flag to 0, you can suppress the extra output and just get the path names:

$ python manage.py findstatic css/base.css --verbosity 0
/home/special.polls.com/core/static/css/base.css
/home/polls.com/core/static/css/base.css

On the other hand, by setting the --verbosity flag to 2, you can get all the directories which were searched:

$ python manage.py findstatic css/base.css --verbosity 2
Found 'css/base.css' here:
  /home/special.polls.com/core/static/css/base.css
  /home/polls.com/core/static/css/base.css
Looking in the following locations:
  /home/special.polls.com/core/static
  /home/polls.com/core/static
  /some/other/path/static

runserver

django-admin runserver [addrport]

Overrides the core runserver command if the staticfiles app is installed and adds automatic serving of static files and the following new options.

--nostatic

User the --nostatic option to disable serving of static files with the statifiles app entirely. This option is only available if the staticfiles app is in your project's INSTALLED_APPS setting.
Example usage:

django-admin runserver --nostatic

Storages存儲(chǔ)

StaticFilesStorage

class storages.StaticFilesStorage

A subclass of the FileSystemStorage storage backend that uses the STATIC_ROOT setting as the base file system location and the STATIC_URL setting respectively as the base URL.
storage.StaticFilesStorage.post_process(paths, **options)
This method is called by the collectstatic management command after each run and gets passed the local storages and paths of found files as a dictionary, as well as the command line options.

Other Helpers

There are a few other helpers outside of the staticfiles app to work with static files:

  1. The django.template.context_processors.static()```` context processor which addsSTATIC_URLto every template context rendered withRequestContext``` contexts.
  2. The builtin template tag static which takes a path and url joins it with the static prefix STATIC_URL. If django.contrib.staticfiles is installed, the tag uses the url() method of the STATICFILES_STORAGE instead.

Static file development view靜態(tài)文件開發(fā)視圖

The static files tools are mostly designed to help with getting static files successfully deployed into production.
靜態(tài)文件工具主要用于幫助將靜態(tài)文件成功部署到生產(chǎn)環(huán)境中侦高。
This usually means a separate, dedicated static file server, which is a lot of overhead to mess with when developing locally.
這通常意味著一個(gè)單獨(dú)的嫉柴,專用的靜態(tài)文件服務(wù)器,這在本地開發(fā)時(shí)是很麻煩的開銷奉呛。
Thus, the staticfiles app ships with a quick and dirty helper view that you can use to serve files locally in development.
因此计螺,staticfiles應(yīng)用程序附帶了一個(gè)快速和臟的幫助視圖,可以使用它在開發(fā)中本地提供文件瞧壮。

views.serve(request, path)

views.serve(request, path)

This view function serves static files in development. This view will only work if DEBUG is True. That's because this view is grossly inefficient and probably insecure. This is only intended for local development, and should never be used in production.
This view is automatically enabled by runserver (with a DEBUG
setting set to True). To use the view with a different local development server, add the following snippet to the end of your primary URL configuration:

from django.conf import settings
from django.contrib.staticfiles import views

if settings.DEBUG:
    urlpatterns += [
        url(r'^static/(?P<path>.*)$', views.serve),
    ]

Note, the beginning of the pattern (r'^static/') should be yourSTATIC_URL setting.

urls.staticfiles_urlpatterns()

urls.staticfiles_urlpatterns()

This will return the proper URL pattern for serving static files to your already defined pattern list. Use it like this:

from django.contrib.staticfiles.urls import staticfiles_urlpatterns

# ... the rest of your URLconf here ...

urlpatterns += staticfiles_urlpatterns()

This will inspect your STATIC_URL setting and wire up the view to serve static files accordingly. Don’t forget to set the STATICFILES_DIRS setting appropriately to let django.contrib.staticfiles know where to look for files in addition to files in app directories.

Refer to: https://docs.djangoproject.com/en/1.11/ref/contrib/staticfiles/

Managing static files(e.g. images,JS,CSS)

Websites generally need to serve additional files such as images, JavaScript, or CSS. In Django, we refer to these files as 'static files'. Django provides django.contrib.staticfiles to help you manage them.

Configuring static files

  1. Make sure that django.contrib.staticfiles is included in your INSTALLED_APPS.
  2. In your settings file, define STATIC_URL, for example:
STATIC_URL = '/static/'
  1. In your templates, either hardcode the url ike /static/my_app/example.jpg or, preferably, use the static template tag to build the URL for the given relative path by using the configured STATICFILES_STORAGE storage(this makes it much easier when you want to switch to a content delivery network(CDN) for serving static files).
{% load static %}
![]({% static )
  1. Store your static files in a folder called static in your app. For example, my_app/static/my_app/example.jpg

In addition to these configuration steps, you will also need to actually serve the static files.
During development, if you use django.contrib.staticfiles, this will be done automatically by runserver when DEBUG is set to True(see django.contrib.staticfiles.views.serve()).
This method is grossly inefficient and probably insecure, so it is unsuitable for production.

Your project will probably also have static asserts that aren't tied to a particular app. In addition to using a static/ directory inside your apps, you can define a list of directories(STATICFILES_DIRS) in your settings files where Django will also look for static files. For example:

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

Serving static files during development

If you use django.contrib.staticfiles as explained above, runserver will do this automatically when DEBUG is set to True. If you don't have django.contrib.staticfiles in INSTALLED_APPS, you can still manually serve static files using the django.views.static.serve() view.
This is not suitable for production use!
For example, if your STATIC_URL is defined as /static/, you can do this by adding the following snippet to your urls.py:

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)
Note

Note: This helper function works only in debug mode and only if the given prefix is local(e.g. /static/) and not a URL(e.g. http://static.example.com/)

Also this helper function only serves the actual STATIC_ROOT folder; it does not perform static files discovery like django.contrib.staticfiles.

Serving files uploaded by a user during development

During development, you can serve user-uploaded media files from MEDIA_ROOT using the django.views.static.serve() view.
This is not suitable for production use!
For example, if your MEDIA_URL is defined as /media/, you can do this by adding the follwing snippet to your urls.py:

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

參考文章:

  1. https://docs.djangoproject.com/en/1.11/ref/contrib/staticfiles/
    2.https://docs.djangoproject.com/en/1.11/howto/static-files/
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末登馒,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子咆槽,更是在濱河造成了極大的恐慌陈轿,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,755評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件秦忿,死亡現(xiàn)場(chǎng)離奇詭異麦射,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)灯谣,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門潜秋,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人胎许,你說(shuō)我怎么就攤上這事峻呛。” “怎么了呐萨?”我有些...
    開封第一講書人閱讀 165,138評(píng)論 0 355
  • 文/不壞的土叔 我叫張陵杀饵,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我谬擦,道長(zhǎng)切距,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,791評(píng)論 1 295
  • 正文 為了忘掉前任惨远,我火速辦了婚禮谜悟,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘北秽。我一直安慰自己葡幸,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,794評(píng)論 6 392
  • 文/花漫 我一把揭開白布贺氓。 她就那樣靜靜地躺著蔚叨,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上蔑水,一...
    開封第一講書人閱讀 51,631評(píng)論 1 305
  • 那天邢锯,我揣著相機(jī)與錄音,去河邊找鬼搀别。 笑死丹擎,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的歇父。 我是一名探鬼主播蒂培,決...
    沈念sama閱讀 40,362評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼榜苫!你這毒婦竟也來(lái)了护戳?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,264評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤单刁,失蹤者是張志新(化名)和其女友劉穎灸异,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體羔飞,經(jīng)...
    沈念sama閱讀 45,724評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡肺樟,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,900評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了逻淌。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片么伯。...
    茶點(diǎn)故事閱讀 40,040評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖卡儒,靈堂內(nèi)的尸體忽然破棺而出田柔,到底是詐尸還是另有隱情,我是刑警寧澤骨望,帶...
    沈念sama閱讀 35,742評(píng)論 5 346
  • 正文 年R本政府宣布硬爆,位于F島的核電站,受9級(jí)特大地震影響擎鸠,放射性物質(zhì)發(fā)生泄漏缀磕。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,364評(píng)論 3 330
  • 文/蒙蒙 一劣光、第九天 我趴在偏房一處隱蔽的房頂上張望袜蚕。 院中可真熱鬧,春花似錦绢涡、人聲如沸牲剃。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,944評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)凿傅。三九已至缠犀,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間狭归,已是汗流浹背夭坪。 一陣腳步聲響...
    開封第一講書人閱讀 33,060評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工文判, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留过椎,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,247評(píng)論 3 371
  • 正文 我出身青樓戏仓,卻偏偏與公主長(zhǎng)得像疚宇,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子赏殃,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,979評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容

  • 處理靜態(tài)文件敷待,尤其是在開發(fā)時(shí),是一件很頭疼的事情仁热。在這篇文章中榜揖,我們將會(huì)討論一些設(shè)置,目錄結(jié)構(gòu)和他們之間的相互影響...
    51reboot閱讀 1,677評(píng)論 0 1
  • 此段內(nèi)容簡(jiǎn)要來(lái)自自強(qiáng)學(xué)堂的教程詳情請(qǐng)查詢自強(qiáng)學(xué)堂 一抗蠢、 后臺(tái)的運(yùn)作流程 接收request請(qǐng)求 處理數(shù)據(jù) 獲取請(qǐng)求...
    coder_ben閱讀 5,246評(píng)論 6 56
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理举哟,服務(wù)發(fā)現(xiàn),斷路器迅矛,智...
    卡卡羅2017閱讀 134,659評(píng)論 18 139
  • 已經(jīng)同步到gitbook妨猩,想閱讀的請(qǐng)轉(zhuǎn)到gitbook: Django 1.10 中文文檔 Writing you...
    leyu閱讀 304評(píng)論 0 0
  • 那是大年初六的清晨,我們急急忙忙趕到爺爺家時(shí)秽褒,還記得奶奶站在爺爺?shù)拇策吅瑁罩鵂敔數(shù)氖郑贿吥ㄑ蹨I一邊啞著嗓子告訴...
    鄧噔噔噔閱讀 290評(píng)論 0 0