Django: the names and values โ€‹โ€‹of the fields of the model model of the template in the template

Possible duplicate:
Django - Iterate the names and values โ€‹โ€‹of the fields of a model instance in a template

Hi,

I am trying to list the fields and corresponding values โ€‹โ€‹of common Django models in templates. However, I can not find a built-in solution for a fairly common problem. I am pretty close to a solution, but cannot find a way out.

view.py Code:

def showdetails(request, template): objects = newivr1_model.objects.all() fields = newivr1_model._meta.get_all_field_names() return render_to_response(template, {'fields': fields,'objects':objects}, context_instance=RequestContext(request)) 

pattern code:

  <table> {% for object in objects %} <tr> {% for field in fields %} <td> <!-- {{ object.field }} /*This line doesn't work*/ --> </td> {% endfor %} </tr> {% endfor %} </table> 

What should I do in the missing line of the template to get the value of Object.field?

Any best DRY methods are also welcome.

+7
source share
2 answers

Unfortunately, you cannot search in the template.

You will have to deal with this in a submission.

 def showdetails(request, template): objects = newivr1_model.objects.all() for object in objects: object.fields = dict((field.name, field.value_to_string(object)) for field in object._meta.fields) return render_to_response(template, { 'objects':objects }, context_instance=RequestContext(request)) 

Template

 {% for object in objects %} <tr> {% for field, value in object.fields.iteritems %} <td>{{ field }} : {{ value }}</td> {% endfor %} </tr> {% endfor %} 
+4
source

You need to create your own filter that will work like getattr in python and use it in a template:

 {{ object|getattribute:field }} 

Here's how to do it: Performing a getattr () style lookup in a django template

But I do not think this is a really good idea. Try to make this logic in the view, for example:

 object_values = [] for object in objects object_values.append([]) for field in fields: object_values[-1].append(getattr(object, field)) return render_to_response(template, {'object_values': object_values}, context_instance=RequestContext(request)) 

and in the template:

 <table> {% for values in object_values %} <tr> {% for value in values %} <td> {{ value }} </td> {% endfor %} </tr> {% endfor %} </table> 

The Django template system does not provide many functions (filters) because you have to do all the logic in the views. The template should contain only data.

+2
source

All Articles