I need to display a table from my database with Django. The obvious way is to manually type in the table headings and loop through query results of model.objects.all()
. However, being quite lazy, I want to do this automatically, i.e. load all fields from model through introspection to display as column headings and load all field values to display as rows. This approach can also save me some time later because I don't have to update my template code when my model changes. I got it to work but there are two problems:
Here is my code. Please note that the code works fine so I'll skip all the imports as they are correct:
views.py I use serializers to serialize the data, a trick I read somewhere on stackoverflow
def index(request):
fields = MyModel._meta.fields
data = serializers.serialize("python", MyModel.objects.all())
context_instance = RequestContext(request, {
'data' : data,
'fields' : fields,
})
return TemplateResponse(request, 'index.html', context_instance)
template/index.html: note that I have to slice off the ID column by slicing off the first element of the fields list
{% with fields|slice:"1:" as cached_fields %}
<table>
<thead>
<tr>
{% for field in cached_fields %}
<th>{% get_verbose_name field %}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for instance in data %}
<tr>
{% for field in cached_fields %}
<td>{% get_value_from_key instance.fields field %}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
{% endwith %}
templatetags/extra_tags.py
# tag to get field's verbose name in template
@register.simple_tag
def get_verbose_name(object):
return object.verbose_name
# tag to get the value of a field by name in template
@register.simple_tag
def get_value_from_key(object, key):
# is it necessary to check isinstance(object, dict) here?
return object[key.name]
serializers.serialize("json
or xml", Model.objects.all())
formats return the id field; probably not what you are looking for but some of the jQuery grid plugins can further automate the task.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With