I need to display a table from my database using Django. The obvious way is to manually enter the table headers and view the results of the model.objects.all() query. However, being pretty lazy, I want to do this automatically, i.e. Download all fields from the model through introspection to display them as column headers and load all field values ββto display as rows. This approach can also save me some time, because I do not need to update the template code when changing my model. I got it for work, but there are two problems:
- I cannot find to load the value of the AutoField (id) field, so I need to cut off the identifier column.
- The code looks pretty dirty, especially using random template tags.
Here is my code. Please note that the code works fine, so I will skip all imports if it is right:
views.py I use serializers to serialize data, a trick I read somewhere in 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 need to cut off the identifier column by cutting off the first element of the field 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 verbose name in template @register.simple_tag def get_verbose_name(object): return object.verbose_name
Lim H.
source share