How to fetch / retrieve images in django

How to fetch image from database in django?

Note : In django, we also store the path of the image in the database and not only the image name

First we will create a path to call the function and write the code to fetch the image/data. Open the in the app and add the below code:


Now create a function index in the views file as shown below.

def index(request):
    products = Item.objects.all()
    context = {'products':products}
    return render(request'products/index.html'context)

Create a template to display the images. Here we have index.html as the template and the code will be as given below:

{% extends 'products/layouts/main.html' %}
{% load static %}

{% block content %}

<section class="section">
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-10">
                <div class="card">
                    <div class="card-header">
                        <h1 class="fw-bold">Image CRUD in Django</h1>
                    <div class="card-body">
                        <table class="table table-bordered table-striped">
                                {% for p in products %}
                                        <td>{{ }} </td>
                                        <td>{{ }} </td>
                                        <td>{{ p.description }} </td>
                                        <td>{{ p.price }} </td>
                                        {% if p.image %}
                                                <img src="{{ p.image.url }}" alt="" class="prod-size">
                                        {% else %}
                                                <img src="{% static 'images/product.png' %}" alt="" class="prod-size">
                                        {% endif %}
                                            <a href="#" class="btn btn-success badge">EDIT</a>
                                            <a href="#" class="btn btn-danger badge">Delete</a>
                                {% endfor %}
{% endblock content %}

{% block scripts %}

{% endblock scripts %}

This will fetch you the images from the database and display it on the index.html file.

Watch the video given above for detailed explaination and video demo. 

© Copyright - 2018 - 2021 | All rights reserved at Funda of Web IT