Home > front end >  Django technology implementation of line breaks by number of posts
Django technology implementation of line breaks by number of posts

Time:06-04

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 >
    <h2 align="center"> Top </h2>
</div>
<div >
    <div >
        {% for p in post %}
        <div  style="width: 16rem;">
            <img src="http://placeimg.com/600/600/any"  alt="...">
            <div >
                <h5 > {{ p.title }}</h5>
                <p > {{ p.explain }}</p>
                <p> {{ p.price }}</p>
            </div>
        </div>
        {% endfor %}
    </div>

CodePudding user response:

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 >
    <div >
        {% for p in post %}
        <div  style="width: 16rem;">
            <img src="http://placeimg.com/600/600/any"  alt="...">
            <div >
                <h5 > {{ p.title }}</h5>
                <p > {{ 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 >
        {% endif %}

        {% endfor %}
    </div>
</div>
  • Related