Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display table of objects django

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:

  1. I can't find away to load the AutoField field (id) value so I have to slice off the ID column.
  2. The code looks quite messy especially with the use of random template tags.

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]
like image 567
Lim H. Avatar asked Jan 30 '13 23:01

Lim H.


1 Answers

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.

like image 59
Vidul Avatar answered Sep 29 '22 12:09

Vidul