Display django object table

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 # 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] 
+7
source share
3 answers

Hooray! I found a job around thanks to Vidul Petrov's suggestion on serializing data in json, which allows me to load the pk field as well. It still seems too tame and hacky (and verbose), but I think I'm getting closer. Please help me reprocess this code.

views.py Serialize the data into a list of JSON objects and parse it in a list of dictionaries to pass it to the template

 from django.utils import simplejson as json def index(request): fields = MyModel._meta.fields data = json.loads(serializers.serialize("json", MyModel.objects.all())) def parse_data(data): result = [] # flatten the dictionary def flatten_dict(d): """ Because the only nested dict here is the fields, let just remove the 'fields' suffix so that the fields can be loaded in template by name """ def items(): for key, value in d.items(): if isinstance(value, dict): for subkey, subvalue in flatten_dict(value).items(): yield subkey, subvalue else: yield key, value return dict(items()) for d in data: # change the 'pk' key name into its actual name in the database d[Employee._meta.pk.name] = d.pop('pk') # append the flattend dict of each object field-value to the result result.append(flatten_dict(d)) return result context_instance = RequestContext(request, { 'data' : parse_data(data), 'fields' : fields, }) return TemplateResponse(request, 'index.html', context_instance) 

template / index.html Now the template is much nicer

 <table> <thead> <tr> {% for field in cached_fields %} <th>{% get_verbose_name field %}</th> {% endfor %} </tr> </thead> <tbody> {% for d in data %} <tr> {% for field in fields %} <td>{% get_value_from_key d field %}</td> {% endfor %} </tr> {% endfor %} </tbody> </table> 
+2
source

serializers.serialize("json or xml", Model.objects.all()) formats return an id field; probably not what you are looking for, but some of the jQuery grid plugins can further automate the task.

+6
source

Take a look at this to automate a lot of this for you from your models. http://django-tables2.readthedocs.org/en/latest/

+5
source

All Articles