Django - For loop brings QuerySet but can't get individual data (as if blank) in HTML template

Viewed 62

I have a django project. Some tables with some info already in place.

I can't see the individual data when applying a FOR LOOP

I revised the code. Looked it up and found no apparent mistake.

Can anyone help me?

Views.py:

from django.shortcuts import render
from .models import Client, Address

main_title = 'Company Name'

def home(request):
    client_list = Client.objects.all()
    address_list = Address.objects.all()
    contex = {
        'address_list' : address_list,
        'main_title'   : main_title,
        'client_list'  : client_list, 
    }
    return render(request, 'home.html', contex)

in home.html

{% for i in address_list %}
   <li>{{ i }}</li>
{% endfor %}

And all I see when going in the browser are the bullet points

*
*

The source code in the browser is loading as:

<ul>
   <li></li>
   <li></li>
</ul>

Now if i change the html code for something without a for loop like

{{ address_list }}

Then the browser shows:

<QuerySet [<Address: THIS IS THE FIRST ADDRESS >, <Address: THIS IS THE SECOND ADDRESS >]>

In other words. The database data is coming trough, But when inside a for loop i gets empty. But I know there are two entries. Because it show two bullet points



EDIT:

After sometime. I striped the code down to the bare minimum and tried to pin-point the problem.

When I finaly figured it out.

my class in the models.py was

class Client(models.Model, RegexValidator):

Once i removed the RegexValidator it worked.

For some stupid reason I tought i had to include RegexValidator in that line.

All solved now

2 Answers

I guess this is because you try to access a dictionary I had a similar problem with nested dictionaries a few weeks before. My solution in the html temaplte looked like follows:

{% for key, value in exampleDict.items %}
<div class="row">
    <h4>Display Key Name {{ key }} </h4>
</div>
<div class="row row-cols-auto pb-2">
        {% for item in value %}
            <div class="col pb-2">
              <p>Item: {{ item }}</p>
            </div>
        {% endfor %}
</div>
{% endfor %}

My code in views.py looked like follows

items = Item.objects.order_by('-date_taken')    
items_dict = {}
         
for item in items:
   date_key = str(item.date_taken.year) + '-' + str(item.date_taken.month)
   if date_key not in items_dict.keys():
      items_dict[date_key] = {}
   items_dict[date_key][item.filename] = item.filename
return render(request, 'items/allitems.html', {'itemsDict': items_dict})

EDIT:

After sometime. I striped the code down to the bare minimum and tried to pin-point the problem.

When I finaly figured it out.

my class in the models.py was

class Client(models.Model, RegexValidator):

Once i removed the RegexValidator it worked.

For some stupid reason I tought i had to include RegexValidator in that line.

All solved now

Related