Iterate over model instance field names and values in template Iterate over model instance field names and values in template python python

Iterate over model instance field names and values in template


model._meta.get_all_field_names() will give you all the model's field names, then you can use model._meta.get_field() to work your way to the verbose name, and getattr(model_instance, 'field_name') to get the value from the model.

NOTE: model._meta.get_all_field_names() is deprecated in django 1.9. Instead use model._meta.get_fields() to get the model's fields and field.name to get each field name.


You can use Django's to-python queryset serializer.

Just put the following code in your view:

from django.core import serializersdata = serializers.serialize( "python", SomeModel.objects.all() )

And then in the template:

{% for instance in data %}    {% for field, value in instance.fields.items %}        {{ field }}: {{ value }}    {% endfor %}{% endfor %}

Its great advantage is the fact that it handles relation fields.

For the subset of fields try:

data = serializers.serialize('python', SomeModel.objects.all(), fields=('name','size'))


Finally found a good solution to this on the dev mailing list:

In the view add:

from django.forms.models import model_to_dictdef show(request, object_id):    object = FooForm(data=model_to_dict(Foo.objects.get(pk=object_id)))    return render_to_response('foo/foo_detail.html', {'object': object})

in the template add:

{% for field in object %}    <li><b>{{ field.label }}:</b> {{ field.data }}</li>{% endfor %}