Guide on Resolving AJAX Filtered Product List Issue with Missing Images in Django Ecommerce Website

I'm facing an issue while implementing filter functionality in my e-commerce project. When I utilized AJAX to generate a filtered product list, all the products are visible but the images aren't showing up.

urls.py:

urlpatterns = [
    path('', views.store, name='home'),
    path('category/<slug:slug>', views.category, name='category'),
    path('product-detail/<int:id>', views.product_detail, name='product_detail'),
    path('cart/', views.cart, name='cart'),
    path('checkout/', views.checkout, name='checkout'),
    path('contact/', views.contact, name='contact'),
    path('signin/', views.signin, name='signin'),
    path('signup/', views.signup, name='signup'),
    path('signout/', views.signout, name='signout'),
    path('filter-data/', views.filter_data, name='filter_data'),
]

views.py:

def filter_data(request):
    category
    colors = request.GET.getlist('color[]')
    sizes = request.GET.getlist('size[]')
    all_products = Product.objects.all()
    
    if len(colors) > 0:
        all_products = all_products.filter(color__id__in=colors)
        print("All Products: ", all_products)
    
    if len(sizes) > 0:
        all_products = all_products.filter(size__in=sizes)
    
    ajax_template = render_to_string('ajax/product-list.html', {'products': all_products})
    return JsonResponse({"data": ajax_template})

ajax code:

$.ajax({
    url: '/filter-data',
    data: _filterObj,
    dataType: 'json',
    beforeSend: function () {
        $(".ajaxLoader").show();
    },
    success: function (res) {
        console.log("This is res", res);
        $("#filteredProducts").html(res.data);
        $(".ajaxLoader").hide();
    }
});

Category.html (This page holds all the products within the category):

<div class="col-lg-9 col-md-9">
    <div class="row" id="filteredProducts">
        {% for product in products %}
        <div class="col-lg-4 col-md-6">
            <div class="product__item">
                <div class="product__item__pic set-bg" data-setbg="{% if product.image %}{{ product.image.url }}{% endif %}">
                    {% if product.labels == 'sale' %}
                    <div class="label sale">{{ product.labels }}</div>
                    {% elif product.labels == 'bestseller' %}
                    <div class="label bestseller">{{ product.labels }}</div>
                    {% else %}
                    <div class="label new">{{ product.labels }}</div>
                    {% endif %}
                    <ul class="product__hover">
                        <li><a href="{% if product.image %}{{ product.image.url }}{% endif %}" class="image-popup"><span class="arrow_expand"></span></a></li>
                        <li><a href="#"><span class="icon_heart_alt"></span></a></li>
                        <li><a href="#"><span class="icon_bag_alt"></span></a></li>
                    </ul>
                </div>
                <div class="product__item__text">
                    <h6><a href="{% url 'product_detail' product.id %}">{{ product.name }}</a></h6>
                    <div class="rating">
                        <i class="fa fa-star"></i>
                        <i class="fa fa-star"></i>
                        <i class="fa fa-star"></i>
                        <i class="fa fa-star"></i>
                        <i class="fa fa-star"></i>
                    </div>
                    <div class="product__price">${{ product.price|floatformat:2 }}</div>
                </div>
            </div>
        </div>
        {% endfor %}
        <div class="col-lg-12 text-center">
            <div class="pagination__option">
                <a href="#">1</a>
                <a href="#">2</a>
                <a href="#">3</a>
                <a href="#"><i class="fa fa-angle-right"></i></a>
            </div>
        </div>
    </div>
</div>

Here's what ajax/product-list.html file looks like.

Even after successfully communicating with the backend using AJAX, the image display problem persists. Please advise if more of my code needs to be shared.

Upon filtering the products, only their details are visible while images remain hidden. Here are some examples for better understanding:

Before filtering: View from database where category is Men

After Filtering: Post-filtering size and color selection from the frontend

Answer №1

To improve your code, it is recommended to update

data-setbg="{% if product.image %}{{ product.image.url }}{% endif %}"
with
<img src="{% if product.image %}{{ product.image.url }}{% endif %}" alt="">
.

<div class="product__item__pic set-bg">
  <img src="{% if product.image %}{{ product.image.url }}{% endif %}" alt=""> 
  {% if product.labels == 'sale' %}
  <div class="label sale">{{ product.labels }}</div>
  {% elif product.labels == 'bestseller' %}
  <div class="label bestseller">{{ product.labels }}</div>
  {% else %}
  <div class="label new">{{ product.labels }}</div>
  {% endif %}
  <ul class="product__hover">
    <li><a href="{% if product.image %}{{ product.image.url }}{% endif %}" class="image-popup"><span class="arrow_expand"></span></a></li>
    <li><a href="#"><span class="icon_heart_alt"></span></a></li>
    <li><a href="#"><span class="icon_bag_alt"></span></a></li>
  </ul>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Shifted picture next to the accompanying words

I have successfully created a slideshow of images using JavaScript. <html> <head> <script language="JavaScript"> var i = 0; var path = new Array(); path[0] = "one.jpg"; path[1] = "two.jpg"; function swapImage() { document.slide ...

Send information to a different tab using ajax

My goal is to send data from order.php to print.php when a user clicks a button. I have attempted to do this using jQuery AJAX, but keep receiving a 500 Internal Server Error. Can someone please help me troubleshoot? This is my latest code attempt: $.aja ...

Behat automates the process of populating form fields that are dynamically displayed as 'visible'

I'm facing an issue with a form that has hidden fields. When a user selects a checkbox, some of the hidden form fields are supposed to be revealed using the jQuery function slideToggle(). The code itself is pretty simple and you can see an example her ...

Displaying AJAX response with AngularJS

My Angular script structure is shown below: var myapp = angular.module("Demo",["ngRoute"]) .config(function($routeProvider){ $routeProvider .when ...

Having Trouble Redirecting to Another Page from My Ionic Framework Controller?

Struggling to figure out why my app isn't switching to another page when clicking in my controller. Any help or pointers on what I might be missing or doing wrong would be greatly appreciated! Here's the code snippet from my app.js file: $s ...

A guide on updating URLs that are not enclosed within an anchor tag using JavaScript

In my current scenario, I am dealing with text that includes URL links presented in two different formats. www.stackoverflow.com <a href="http://www.stackoverflow.com">Stack over flow</a> My objective is to create a straightforward function ...

What is the method for retrieving this data using Javascript?

I received this JSON-encoded data: { "error": { "msg":"Concurrent verifications to the same number are not allowed", "code":10 } } and I tried to access the 'msg' value using JavaScript as follows: $("#buttonPhoneSubmit ...

Display the most recent download date in Django along with the number of new entries since the previous download

Within my application, I have successfully implemented a function to download all user information from the database. Additionally, on my HTML page, I want to display the date of the most recent download of the CSV file and indicate how many new profiles h ...

JSRender: A guide on accessing variables from outside the block

I am currently using jsrender to display the details of my JSON object. One thing I'm trying to figure out is how to access an external variable from within the list. Any help would be greatly appreciated. <script id="itemTemplate" type="text/x ...

React's router activeClassName feature fails to apply the active class to child routes

<ul className="right hide-on-med-and-down"> <li><IndexLink to="/" activeClassName="active">ABOUT</IndexLink></li> <li><Link to="blog" activeClassName="active">BLOG</Link></li> <li><Link t ...

The performance of my Ajax callback is not meeting my expectations

It seemed like I had a grasp on how this worked, but clearly not. I am struggling to retrieve a value from a jQuery Ajax request. This is the code snippet causing issues: function initForm() { prefix = getPrefix(country_id); alert(prefix); // &l ...

automating the styling of elements

Hey everyone, I have a specific element that I want to conditionally apply multiple styles to. Initially, I approached it like this: <Text style={[ discountCodeState === '' || !isActiveHandler(value) ? [ ...

Learn the process of uploading a default file with C# in ASP.NET

Is there a way to upload a default file from the client side without having to use the browse button in the file upload control? For example, I want to upload a specific file every time I click a button, without showing the file dialog. Can this be achie ...

Ways to retrieve information from the object received through an ajax request

When making an AJAX request: function fetchWebsiteData(wantedId) { alert(wantedId); $.ajax({ url: 'public/xml/xml_fetchwebsite.php', dataType: 'text', data: {"wantedid": wantedId}, typ ...

What is the best way to render JSON information in JSP with JavaScript?

Using Spring MVC, my controller "Book.java" returns a JSON object. I would like to display the content of the JSON object in a table format in a JSP. How can I achieve this? Here is the function in my controller that returns the JSON object: @Controller ...

What is the best way to store this value in a variable and incorporate it into a conditional statement within a React application?

Seeking assistance in resolving this issue. I am trying to extract the values between the backticks (``) from the span tag and store them in a variable for the logic shown below: ${research.data.codesRelated[1].code} === undefined ? ${research.data.desc ...

Modifying the HTML5 data attribute according to the URL hash

Within my div element, I have this code: <div id="nav-aj" data-options='{"default":'t1","animation": {"duration": 500, "effects": "fade"}}'> </div> I am looking to dynamically adjust the value of the default option based on th ...

The bodyparser in Express seems to be malfunctioning

When configuring my body parser, I implement the following code: const express = require('express') const app = express(); const bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extend ...

What is the best way to transform the pages extracted through the Notion API into slugs?

I'm new to Next.js and Notion API, and I want to create a blog site on my personal website using the Notion API. While I can easily pull the posts, I am facing a challenge in slugifying the endpoint IDs with post titles. When attempting this based on ...

Include a <div> element to display the date in an HTML format, ensuring that the days and months

I am working on a project where I have a list of dates and I need to format them by adding div tags to separate the days, months, and years into different divisions. <div class="campaign">30/11/2016 - <a href="#" target="_blank">Dummy Text& ...