How can you do a for loop with a database?

24 views
Skip to first unread message

Peter T

unread,
Dec 12, 2020, 11:11:30 AM12/12/20
to Django users
Example:
context = (database model)

def index(request):
     render(index.html, context)

HTML Template:

{% for i in context %}
     <h1>{ database.text }</h1>

Andréas Kühne

unread,
Dec 13, 2020, 8:12:30 AM12/13/20
to django...@googlegroups.com
The context needs to be a dictionary.

Something like this would work:
context = {
    ‘items’: Model.objects.all()
}

Then in the template:
{% for item in items %}
  <h1>{{ item.text }}</h1>
{% endfor %}

Here ‘text’ is the property on the database model you want to display.


Regards,


Andréas

12 dec. 2020 kl. 17:11 skrev Peter T <prth...@gmail.com>:

Example:
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/035bd359-0df5-4d1c-b7b7-f4e08584c288n%40googlegroups.com.

Peter T

unread,
Dec 14, 2020, 9:25:54 AM12/14/20
to Django users
is (items) the model name?

Shahprogrammer

unread,
Dec 14, 2020, 9:53:40 AM12/14/20
to Django users
No it is a dictionary representation of your data

Peter T

unread,
Dec 14, 2020, 10:24:33 AM12/14/20
to Django users
I did not realize it was a dictionary haha
Reply all
Reply to author
Forward
0 new messages