0

i have a problem with getting image url in django template. In views file i am getting "product__stock_keeping_unit__image" which is related products' image as below.

data = models.Product.objects.filter(category__slug=slug, product__is_default=True).values("id", "name", "product__sku", "slug", "category__name", "product__store_price", "product__sub_product__units", "product__stock_keeping_unit__image")

in template file i am trying to display image

{% for item in data %}
        <div class="col-lg-3 mb-4 text-center">
            <div class="product-entry border">
                <a href="#" class="prod-img">
                    <img src="{{ item.product__stock_keeping_unit__image.url }}">
                </a>
                <div class="desc">
                    <h2><a href="{% url 'product_detail' item.slug item.product__sku %}">{{ item.name }}</a></h2>
                    <span class="price">${{ item.product__store_price }}</span>
                </div>
            </div>
        </div>
       {% endfor %}

Everything works fine except img field. In the page source i am getting empty string. But when i write <img src="{{ item.product__stock_keeping_unit__image }}"> i am getting image path in page source images/men-shoes.jpg but not add MEDIA_URL /media/images/men-shoes.jpg into path.

Settings.py

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

How can i solve this problem. Thank in advance!

2 Answers 2

0

You have to add the media prefix like so:

src="{% get_media_prefix %}{{ item.product__stock_keeping_unit__image }}">

and set some url settings for development mode like so:

# urls.py

..
urlpatterns = [
   ...
]

# Serving the media files in development mode
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
else:
    urlpatterns += staticfiles_urlpatterns()
Sign up to request clarification or add additional context in comments.

Comments

0

.values(...) returns queryset containing dictionary, see here. Therefore you will not able to access url property of image field.

Use standard django object that exposes property of the image field. You can use following:

Query:

data = models.Product.objects.filter(category__slug=slug, product__is_default=True)

In template

<img src="{{ item.product.tock_keeping_unit.image.url }}">

p.s. you can use select_related for performance

1 Comment

The problem is that my Product table does not store any foreign key. Instead my SubProduct table store product_id so, i can't access item.product.stock_keeping_unit.image.url.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.