简体   繁体   English

MEDIA_URL 在 Django 模板中不起作用

[英]MEDIA_URL not working in Django templates

I'm building a project in Django 3, but the images aren't linking in the files.我正在 Django 3 中构建一个项目,但文件中的图像没有链接。

All images are store in a folder called media & here's the HTML for my logo for example -所有图像都存储在一个名为 media 的文件夹中,例如,我的徽标是 HTML -

<a class="navbar-brand" href="{% url 'index' %}">
<img src="{{ MEDIA_URL}}logo.png" height="70" class="pr-4" alt="Site logo">

Then I've this in my settings -然后我在我的设置中有这个 -

STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

and in my project level URLS I've got -在我的项目级 URLS 中,我得到了 -

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

+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

You should use static folder for the static content like images, css, js etc... and media for the dynamic content like uploads from users, avatar pictures... then you should use this template tag:您应该将 static 内容(如图像、css、js 等)使用 static 文件夹,并将媒体用于动态内容(如用户上传的内容、头像图片),然后您应该使用此模板标签:

{% load static %}

<a class="navbar-brand" href="{% url 'index' %}">
<img src="{% static 'logo.png' %}" height="70" class="pr-4" alt="Site logo">

If you want to use media folder anyways, you need to add this in your urls.py (extracted from here ) in order to make it work fine in local:如果你想使用媒体文件夹,你需要在你的 urls.py 中添加它( 从这里提取),以使其在本地工作正常:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM