Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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 class="redtext">{{ aboutinfo.name }}</p>
<p class="redtext">{{ aboutinfo.details }}</p>
<p class="redtext">{{ aboutinfo.website }}</p>


{% endblock body_block %}

>Solution :

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 class="redtext">{{ company_info.name }}</p>
    <p class="redtext">{{ company_info.details }}</p>
    <p class="redtext">{{ company_info.website }}</p>
{% endfor %}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading