Home > database >  How to insert images from render( , , context) in Django?
How to insert images from render( , , context) in Django?

Time:10-10

guys! New in Django so maybe it's a silly question. I have a .json file that keeps information about shop's clothes including "img". The goal is to otput all the information about products in a single "for loop". So I've written such lines

{% for product in products %}

                <div class="col-lg-4 col-md-6 mb-4">
                    <div class="card h-100">
                        <a href="#">
                            <img class="card-img-top"
                                 src="{% static '{{ product.img }}' %}"  !!! problem is here
                                 alt="">
                        </a>
                        <div class="card-body">
                            <h4 class="card-title">
                                <a href="#"> {{ product.name }} </a>
                            </h4>
                            <h5>{{ product.price }}</h5>
                            <p class="card-text"> {{ product.description }}</p>
                        </div>
                        <div class="card-footer text-center">
                            <button type="button" class="btn btn-outline-success">Отправить в корзину</button>
                        </div>
                    </div>
                </div>

            {% endfor %}

Everything works fine except the line concerns an image. In devtools I get the next path "/static/{{ product.img }}". But in the .json file it looks like "img": "vendor/img/products/Brown-sports-oversized-top-ASOS-DESIGN.png". I am totally confused about that situation and definitely in a bind. I appreciate any help

CodePudding user response:

work with:

<img src="{{ product.img.url }}">

if the image is effective (product.img is not None), and you added the media urls to the urls.py, then it will determine the URL where to fetch the product image.

Note that in production, Django does not serve media files, so in that case you will need to configure the webserver (Apache, Nginx, etc.) to serve media files for you.

  • Related