Home > front end >  How to execute Nested loop in Django Template on single Queryset
How to execute Nested loop in Django Template on single Queryset

Time:02-13

I want to render my query set data on template with a slider. Each slider will contain 3 product query like this enter image description here

But I am unable to to this dynamically with for loop in Django template language. My Template code is

<h4>Latest Products</h4>
                        <div >
                            {% for product in recent_products %}
                                <div >
                                    <a href="#" >
                                        <div >
                                            <img src="{{product.images.url}}" alt="">
                                        </div>
                                        <div >
                                            <h6>{{product.name}}</h6>
                                            <span>{{product.price}} Tk</span>
                                        </div>
                                    </a>
                                </div>
                            {% endfor %}

                        </div>

here is my view function:

def index(request):
    products = Product.objects.all()
    categorys = ProductCategory.objects.all()

    today = timezone.now().date()
    last_day = today - timezone.timedelta(days=7)

    today = datetime.strftime(today, "%Y-%m-%d")
    last_day = datetime.strftime(last_day, "%Y-%m-%d")

    print(last_day)
    recent_products = Product.objects.filter(added_time__range=[last_day, today]).order_by("-added_time")
    context = {
        'products': products,
        'categorys': categorys,
        'recent_products': recent_products
    }
    return render(request, 'index.html', context)

and my model class is:

class ProductCategory(models.Model):
    name = models.CharField(max_length=100)
    image = models.ImageField(blank=True, null=True)
    added_time = models.DateTimeField(auto_now_add=True)
    updated_time = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

class Product(models.Model):
    name = models.CharField(max_length=200)
    price = models.FloatField(blank=True, null=True)
    ratings = models.FloatField(blank=True, null=True)
    number_of_ratings = models.IntegerField(blank=True, null=True)
    images = models.ImageField(blank=True, null=True)
    description = models.TextField(blank=True, null=True)
    # user_review need to be added
    discount_rate = models.IntegerField(default=0)
    available_stock = models.IntegerField(default=0)
    added_time = models.DateTimeField(auto_now_add=True)
    updated_time = models.DateTimeField(auto_now=True)
    category = models.ForeignKey(ProductCategory, on_delete=models.SET_NULL, null=True, blank=True)

    @property
    def discount(self):
        if self.discount_rate > 0:
            discounted_price = self.price - self.price * self.discount_rate / 100
            return discounted_price

CodePudding user response:

If your view submit a queryset it will be static, if recent_products is a queryset of the three latest products then you can't change it this way. I guess there are two solutions which you could implement:

  1. If you don't want to show all products then the most easy way to do this is to make a queryset with a limit like 12 products, then you create a slider with 9 hidden products in it and you can show/hide the products on demand. This is still static, but maybe this will already work for you. The problem here is that you have to limit the queryset at some point. If you have a lot of products and you need to load a image for each one, this option will not work.

  2. The other solution is truly dynamic, more efficient but also a bit more complicated. You could do ajax-requests for the product slider. So your view would not submit any products at all. You have to create another view which deals with ajax requests and submits 3 products, according to the page index. It would need some javascript do the requests and replacing the products and keeping track of the current page. The advantage of this is your page would load faster as it does not need to load all the images and product informations which may be never be seen and you could let the customer browse trough all of your products if they want to.

CodePudding user response:

In your views.py, change

today = timezone.now().date() into

today = timezone.now()

  • Related