Landcross
Landcross

Reputation: 492

Loop over fields in a database row in Django template

I'm new to Django (1.8, Python 3) and I'm trying to build a little website with it.

[for the sake of simplicity, I alter my situation to an imaginary bookstore]

What I want to accomplish is the following: imagine I have a model (database table if you will) that includes of a bunch of data of books. I want to show the data to the user. But I'm lazy and I don't want to specify every field in the template. I want a loop that automaticly loops over every field for a specific book and displays the verbose name and the data.

What I currently have accomplished, is that I can access the data in my template by having this in my views:

book = Book.objects.get(id=book_id)

Where book_id is injected by the url (e.g. site/book/1). So, now I can access every field in the template, e.g. {{ book.name }}, or {{ book.author }}. But, it's a lot of manual work to add a html paragraph for every field.

However, I want something like this in my template (just an example, doesn't have to be exactly that):

{% for field in book %}:
    {{ field.verbose_name }} {{ field.data }}
{% endfor %}

But simply doing that with my current current .get(id=book_id) doesn't work. And, I also can't acces the verbose name.

Also, it would be super nice if the solution also works for relationships, for example:

{% for field in book.author %}:
    {{ field.verbose_name }} {{ field.data }}
{% endfor %}

Where it displays all the data of the author table of the currently selected book.

Anyway, I hope my explanation is clear. I'm not really that great in asking clear questions :(

Thanks!

Upvotes: 3

Views: 4667

Answers (1)

Sayse
Sayse

Reputation: 43300

Now yes, you could abuse meta to get the verbose_name but there isn't any correlation to the data from this

{% for field in book._meta.fields %}
    {{ field.verbose_name }} 
{% endfor %}

I'm not sure how correct this is seeing as Pep8 warnings appear quite often around meta tags (I can't see about this from a template side)

I would encourage you to look into using values

As a small example this will give you a dict that you can iterate over (this example gives the id and name)

Book.objects.filter(id=book_id).values('id', 'name')[0]
{% for key, val in book_fields %}
    {{ key }} {{ val }}
{% endfor %}

The nicer way about this that you only get the fields you actually care about (id isn't much help to everyone sometimes)

If you leave out the fields from values then you do get all of them, but I'm not sure if its the verbose name that is used

Book.objects.filter(id=book_id).values()[0]

Upvotes: 3

Related Questions