Home > Blockchain >  Running a for loop inside html file for specific time in django
Running a for loop inside html file for specific time in django

Time:01-30

I want a for loop to run 2/3 times for this specific model. Lets assume I have 10 data, I want the first 3 one to be shown inside html file through a for loop. Can anyone help me with this one?

This is the 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 file

    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)

inside the html file

{% block body_block %}


<p >{{ aboutinfo.name }}</p>
<p >{{ aboutinfo.details }}</p>
<p >{{ aboutinfo.website }}</p>


{% endblock body_block %}

CodePudding user response:

Instead of just sending single object through context try sending 3 of them:

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

Then you can loop through them inside the templates as follows:

{% for company_info in company_info_objs %}
    <p >{{ company_info.name }}</p>
    <p >{{ company_info.details }}</p>
    <p >{{ company_info.website }}</p>
{% endfor %}
  •  Tags:  
  • Related