My problem
I am making a shopping mall using Django, Bootstrap
I want to implement technology line break when the post becomes 4
I thought if I used col-3 and {$ for %} {% endfor %} it would be divided into four and line breaks. but not working
How can i fix it?
MY models
from django.db import models class Cloth(models.Model): title = models.CharField(max_length=30) explain = models.CharField(max_length=30) price = models.IntegerField(blank=True) def __str__(self): return self.title
My views
from django.shortcuts import render from .models import Cloth def index(request): post = Cloth.objects.all() return render(request, 'Blog/index.html', {'post':post})
My urls
from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ]
My index.html
<div class="container py-3"> <h2 align="center"> Top </h2> </div> <div class="container py-2 px-1"> <div class="row"> {% for p in post %} <div class="card col-3" style="width: 16rem;"> <img src="http://placeimg.com/600/600/any" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title"> {{ p.title }}</h5> <p class="card-text"> {{ p.explain }}</p> <p> {{ p.price }}</p> </div> </div> {% endfor %} </div>
Advertisement
Answer
The problem is you are putting everything into a single row div.
You can use divisibleby and forloop.counter to test if the record number is a multiple of four, and, if so, to close your row div and open another in your template. See the docs for further details on these template tools.
Index.html
<div class="container py-2 px-1"> <div class="row"> {% for p in post %} <div class="card col-3" style="width: 16rem;"> <img src="http://placeimg.com/600/600/any" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title"> {{ p.title }}</h5> <p class="card-text"> {{ p.explain }}</p> <p> {{ p.price }}</p> </div> </div> {% if forloop.counter|divisibleby:"4" %} <!-- here we close the row and then reopen another --> </div> <div class="row"> {% endif %} {% endfor %} </div> </div>