django 如何在HMTL中使用媒體media_url中指定的路徑
第一種:
一、
setting.py里,一般圖片或者文件上傳路徑都是是以下設置,
MEDIA_URL = '/media/' #訪問路徑
MEDIA_ROOT = os.path.join(BASE_DIR, 'media') #上傳路徑
二、
項目app里url.py,設置如下
from django.conf import settings
from django.views.static import serve
urlpatterns = [url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT})]
三、
如果想在html中調用media_url的訪問路徑
# 首先在setting.py中 TEMPLATES 下面的 'context_processors': 里面添加 'django.template.context_processors.media', TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'front/templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug',
在html中即可如此調用
<body><img src = "{{ MEDIA_URL }}{{ceshi}}"></body>
如果沒有第三步設置,html中只能使用以下方式調用:
<img src = "/media/{{ceshi}}">
第二種:需要django版本>=1.7
from django.conf import settings from django.conf.urls.static import static urlpatterns = patterns('', # ... the rest of your URLconf goes here ... ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) 然后通過添加啟用media context_processors inTEMPLATE_CONTEXT_PROCESSORS TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ #here add your context Processors 'django.template.context_processors.media', ], }, }, ] 現在每個RequestContext都包含一個變量MEDIA_URL 現在你可以在你的訪問中訪問它 template_name.html <p><img src="{{ MEDIA_URL }}/image_001.jpeg"/></p>
