简体   繁体   中英

MEDIA_URL not working in Django templates

I'm building a project in Django 3, but the images aren't linking in the files.

All images are store in a folder called media & here's the HTML for my logo for example -

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

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:

{% 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:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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