Django技术实现按帖子数换行

Django technology implementation of line breaks by number of posts

我的问题

我正在使用 Django 制作一个购物中心,Bootstrap

我想在post变成4

时实现技术换行

我想如果我使用 col-3 和 {$ for %} {% endfor %} 它会被分成四个和换行符。但不工作

我该如何解决?

我的模型

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

我的看法

from django.shortcuts import render
from .models import Cloth

def index(request):
    post = Cloth.objects.all()
    return render(request, 'Blog/index.html', {'post':post})

我的网址

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),

]

我的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>

问题是您将所有内容都放在一行中 div。

您可以使用 divisibleby 和 forloop.counter 来测试记录号是否是四的倍数,如果是,则关闭您的行 div 并在你的模板。有关这些模板工具的更多详细信息,请参阅 docs

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>