Listview Iterate over List

19 views
Skip to first unread message

sebasti...@gmail.com

unread,
Apr 7, 2021, 2:02:04 PM4/7/21
to Django users
Hello,

i want to create a Listview like this:

class HistorieListView(ListView):
    model = Address
    template_name = 'marketing/liststandardtemplate.html'
    fieldlist = ('id', 'lastname', 'firstname')

now i want in liststandardtemplate.html that i iterate in tablebody over fieldlist:

<tbody>
                            {%for element in object_list%}
                            <tr>
                               {% for field in fieldlist %}
                                <td>
                                {{ element.field }}
                                </td>
                               {% endfor %}
                            </tr>
                            {% endfor %}
                            </tbody>

but   {{ element.field }} won't work. This is absolut clear why but i have no idea how i can create such a template....

I want a flexible Listview Template that i can use with every model and can set in fieldlist which columns are shown in listview. When field ist a foreignkey field then __str__ from related model is shown...

Ryan Nowakowski

unread,
Apr 8, 2021, 5:47:52 PM4/8/21
to Django users
On Wed, Apr 07, 2021 at 11:02:04AM -0700, sebasti...@gmail.com wrote:
> i want to create a Listview like this:
>
> class HistorieListView(ListView):
> model = Address
> template_name = 'marketing/liststandardtemplate.html'
> fieldlist = ('id', 'lastname', 'firstname')
>
> now i want in liststandardtemplate.html that i iterate in tablebody over
> fieldlist:
>
> <tbody>
> {%for element in object_list%}
> <tr>
> {% for field in fieldlist %}
> <td>
> {{ element.field }}
> </td>
> {% endfor %}
> </tr>
> {% endfor %}
> </tbody>
>
> but {{ element.field }} won't work. This is absolut clear why but i have
> no idea how i can create such a template....

You'll probably need to perform a getattr lookup in your template here.
Found this little solution on the ole' stackoverflow:

https://stackoverflow.com/a/1112236/226697
Reply all
Reply to author
Forward
0 new messages