Satheesh Panduga
Satheesh Panduga

Reputation: 818

How to set image url of a div as its background in Django template

I have below code in my template, I would like to dynamically set background url value that come from django view

<div class="profpic" style="background:url('{{ MEDIA_URL }}{{ objects.profpicpath }}');background-size:cover">
</div>

This gives the output as from the source code in browser as below

<div class="profpic" style="background-image:url('/UsersOpr/documents/documents/20150718/bd55adcd-9360-4a05-b506-18373805b600_20150718_152906.jpg');background-size:cover">
</div>

SO,

{{ MEDIA_URL }} is rendered with value '/UsersOpr/'

{{ objects.profpicpath }} with value 'documents/documents/20150718/bd55adcd-9360-4a05-b506-18373805b600_20150718_152906.jpg'

What else am I missing ?

Here is my Settings.py

MEDIA_ROOT = '//192.xxx.xxx.xxx/d$/UsersOpr/'
MEDIA_URL = '/UsersOpr/'

I was searching extensively in the Internet on how to set the image url that is dynamically populated from django view and to be rendered in django template, but couldn't get through - tried using {{ STATIC_URL }} , {{ MEDIA_URL }} etc., and image path etc.,. but couldn't get

Upvotes: 0

Views: 942

Answers (1)

Satheesh Panduga
Satheesh Panduga

Reputation: 818

After quite a lot of search, I could solve it finally. Thought this could be helpful to someone who come across this scenario with the Media uploads.

Settings.py should contain below for sure :

TEMPLATE_CONTEXT_PROCESSORS = (
'django.template.context_processors.debug',
'django.template.context_processors.request',
"django.core.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.media",  # Mandatory for Media file uploads
"django.core.context_processors.static",
)

MEDIA_ROOT = '//ipaddress or localhost/.../media/'
MEDIA_URL = '/media/'

urls.py

from django.conf import settings

if settings.DEBUG:
    urlpatterns += patterns('',
    (r'^media/(?P<path>.*)$', 'django.views.static.serve', {
    'document_root': settings.MEDIA_ROOT}))

When calling in the template.. it should be like

{{ MEDIA_URL }}{{ object.imagepath }} 

and make sure that the media folder has read permissions to the user accessing the image object

Upvotes: 1

Related Questions