djangobootstrap-carousel

Django Bootstrap Carousel 4 items at a time


Good day SO.

I want to use Bootstrap Carousel with Django and display 4 items per carousel-item. (With a maximum of 20 items)

First on my views, I have created a view:

items = AllItems.objects.all().order_by('-id')
context['items'] = items 

Next, on my template I believe I need to loop through my items like this

<div class="carousel-inner">
    {% for item in items%}
        {% if forloop.counter|divisibleby:4 == 1 or forloop.first %} // Add the opening div
            <div class="carousel-item"> 
        {% endif %}
            <div class="item">{{item.item_title}}</div>              // Add the items
        {% if forloop.counter|divisibleby:4 == 0 or forloop.last %}  // Add the closing div
            </div>
        {% endif %}
    {% endfor %}
</div>

But reality is different. Hoping to ask your logic on this type of scenario.

Do I need to use paginator for this? Though my second option was to use paginator, then use ajax and jquery to create div per carousel-item.


Solution

  • You can make use of slice

    <ul>
      <div class="carousel-inner">
        {% for item in items|slice:":4"%} <!-- Shows first four objects -->
          <div class="carousel-item"> 
            <div class="item">{{item.item_title}}</div>
          </div>
        {% endfor %}
      </div>
    </ul>