运行 html 文件内的 for 循环用于 django 中的特定时间

Running a for loop inside html file for specific time in django

对于这个特定的模型,我想要一个 运行 2/3 次的 for 循环。假设我有 10 个数据,我希望前 3 个数据通过 for 循环显示在 html 文件中。谁能帮我解决这个问题?

这是models.py

class CompanyInformation(models.Model):
name = models.CharField(max_length=50)
details = models.TextField(max_length=50)
website = models.CharField(max_length=50, null=True, blank=True)
social_fb = models.CharField(max_length=50, null=True, blank=True)
social_ig = models.CharField(max_length=50, null=True, blank=True)
social_twitter = models.CharField(max_length=50, null=True, blank=True)
social_youtube = models.CharField(max_length=50, null=True, blank=True)

def __str__(self):
    return self.name

views.py 文件

    from django.shortcuts import render
from .models import *
# Create your views here.

def aboutpage(request):
    aboutinfo = CompanyInformation.objects.all()[0]
    context={
        'aboutinfo' : aboutinfo,
    }
    return render(request, 'aboutpage.html', context)

在 html 文件中

{% block body_block %}


<p class="redtext">{{ aboutinfo.name }}</p>
<p class="redtext">{{ aboutinfo.details }}</p>
<p class="redtext">{{ aboutinfo.website }}</p>


{% endblock body_block %}

与其仅通过上下文发送单个对象,不如尝试发送其中的 3 个对象:

company_info_objs = CompanyInformation.objects.all()[:3]
context={
        'company_info_objs' : company_info_objs,
    }

然后您可以在模板中循环遍历它们,如下所示:

{% for company_info in company_info_objs %}
    <p class="redtext">{{ company_info.name }}</p>
    <p class="redtext">{{ company_info.details }}</p>
    <p class="redtext">{{ company_info.website }}</p>
{% endfor %}