1

I am using a for loop in an HTML Template, it recognizes the fact that they are there but it does not show them in the page like it should.

my views:

    person = []
    x = people.objects.filter(deal='q')
    for person in x:
         print(person.name)
         if person.paid_status == True:
             person.append(lender)
     return render(request, '.html', {'person': person})

my template:

<div>
    {% if person %}
        There are {{ person|length }} persons.
        {% for p in person %}
    <p> {{ p.name }} </p>
        {% endfor %}
    {% else %}
         <p> As of now no persons have appeared. </p>
    {% endif %}
</div>

in the console it prints the persons name correctly so I am confused why it does not work in the HTML

All I see is that there are 2 persons(which is correct) but then it does not list them.

Thanks in advance.

1 Answer 1

2

You are overwriting the variable person inside your loop.

Change the list person to persons and it should work fine.

Your view:

persons = []
x = people.objects.filter(deal='q')
for person in x:
     if person.paid_status == True:
         persons.append(person)
 return render(request, '.html', {'persons': persons})

Your template:

<div>
    {% if persons %}
        There are {{ persons|length }} persons.
        {% for p in persons %}
        <p> {{ p.name }} </p>
        {% endfor %}
    {% else %}
         <p> As of now no persons have appeared. </p>
    {% endif %}
</div>
Sign up to request clarification or add additional context in comments.

2 Comments

This worked, by overwhelming the variable what did you mean?
On the first line you do person = [], then in the loop you do for person in x:. When you do that, the variable person being used to iterate the list x is overwriting the list person you just created 2 lines above. If my answer is the correct answer, please, mark as the correct one, it would help me a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.