I've read a lot of question and article but can't find what I'm missing.
Here is my conf :
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(os.path.dirname(__file__),'static').replace('\\', '/'),
)
urls.py
urlpatterns = [
url(r'^$', include('home.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^artist/', include('artists.urls')),
url(r'photo/', include('photo.urls'))
]
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Whatever, my media are served, cause when I go to http://localhost:8000/media/path/to/image.jpg, i have my image.
But when in template I go like this :
<img class="avatar secondary-content" src="{{MEDIA_URL}}{{artist.artist_image}}">
I only have the image path. When I change in html {{MEDIA_URL}}
by '/media/', it works.
So it seems my MEDIA_URL
is not set in template and as far as I've searched, I can't see what I missed.
I'm on django 1.8.2. If you need any informations, just ask me.
You need to define the django.template.context_processors.media
template context processor in your settings for MEDIA_URL
variable to be present in the template context.
If this processor is enabled, every
RequestContext
will contain a variableMEDIA_URL
, providing the value of theMEDIA_URL
setting.
Including this in your settings
will include MEDIA_URL
in the template context. It is not included by default in Django 1.8 settings. We need to set it explicitly.
context_processors = [
...
'django.template.context_processors.media', # set this explicitly
]
models.ImageField
has a property called url
which gives you the browsable path of your image.
You should be using artist.artist_image.url
instead of prepending MEDIA_URL
to your image name manually:
<img class="avatar secondary-content" src="{{artist.artist_image.url}}" />
--
Make sure artist_image
is not None
, otherwise calling .url
throws an exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With