Запуск цикла for внутри html-файла в течение определенного времени в django
Я хочу, чтобы цикл for выполнялся 2/3 раза для этой конкретной модели. Допустим, у меня есть 10 данных, я хочу, чтобы первые 3 были показаны в html-файле через цикл for. Может ли кто-нибудь помочь мне с этим?
Это 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 %}