images from media file wont get displayed in django template
For me, I did the following two things:
Define media url in the settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
and then in the project's urls.py, defined serving url for development and production purpose:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('django_app.urls')),
]
# Serving the media files in development mode
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
else:
urlpatterns += staticfiles_urlpatterns()
then you can reference the image in the media folder in the template like this:
<img src="media/path_to_image" />
Note: Don't forget to set the DEBUG flag to False in the settings.py for production.
Oh FFS....
aperently it's
MEDIA_URL = '/media/'
NOT
MEDIA_URL = 'http://127.0.0.1:8000/media/'
...despite #'http://127.0.0.1:8000/media/'
being written right next to it
working img link looks like so:
<img src="/media/images/photo_1.JPG" />
you definitely need the:
static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
in the url file also
if you are looking for display images in development environment try this:
settings.py
SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(SITE_ROOT, 'static')
MEDIA_URL = '/static/'
STATIC_ROOT = os.path.join(SITE_ROOT, 'statics')
STATIC_URL = '/statics/'
urls.py
# somebody import this from settings
SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
urlpatterns += patterns('',
url(r'^static/(?P<path>.*)$','django.views.static.serve',
{'document_root': os.path.join(SITE_ROOT, 'static')})
)
html view file *.html:
<img src="{{ MEDIA_URL }}img/content_top_edit_form.png">
this means we have a img folder in static folder. in your case you can change this by
if you see your browser html must be seen like this:
<img src="/static/img/content_top_edit_form.png">