Luke Greiz
Luke Greiz

Reputation: 21

Django image (media) path don't display correctly in template

In my project i had set my media folder like this:

settings.py

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

urls.py

urlpatterns = [
    ....
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

then in my models.py i create a class like this one:

class PD_Pictures(models.Model):
    pic_IDmod = models.ForeignKey(PD_Models, related_name='modello')
    pic_image = models.ImageField()
    pic_descr = models.CharField(max_length=50)

 def __str__(self):
    return self.pic_descr

at this point in my function in views.py I extract all values in db related to PD_Picture:

prod_img = PD_Pictures.objects.all()
.....
return render(
    request,
    'base_catalog.html',
    {
        'bike_mod': bike_models,
        'prod_img': prod_img,
        'cat_list': cat_list,
        'menu_list': menu_list['menu'],
        'pcontent': menu_list['cont'],
        'form': c_form
    },
    context
)

and in my template, i would ti display related images:

{% for pic in prod_img %}
    <div class="4u">
        <span class="image fit"
            <img src="{{ pic.pic_image }}" alt="" />
        </span>
    </div>
{% endfor %}

Well, at this point when I insert a new image in db, in table the path is newimage.jpg, physically on my server the image was stored in /media/newimage.jpg, how can I extract the value from the table and concatenate to the media path in my template? (<server>/media/newimage.jpg)

I have tried to use upload_to='/models/' in my ImageField but the only effect is to save image into another model folder into main model.

Upvotes: 0

Views: 1306

Answers (3)

AleMal
AleMal

Reputation: 2087

From django official doc:

FieldFile.url A read-only property to access the file’s relative URL by calling the url() method of the underlying Storage class.

if you try to print in your template {{ pic.pic_image }} you'll receive the db field value, while with {{ pic.pic_image.url }} the url() method from django.core.files.storage.Storage will call, and your base settings would seem to be correct

Upvotes: 1

UserGraund
UserGraund

Reputation: 310

just try like this

{% for pic in prod_img %} <img src="{{ pic.pic_image.url }}" alt="" /> {% endfor %}

Upvotes: 2

Marin
Marin

Reputation: 1121

Can you make this into your template and see what path is given?

{% for pic in prod_img %}
  <p>{{ pic.pic_image }</p>
{% endfor %}

Upvotes: 0

Related Questions