how to render a Queryset into a table template-django


Question

I have a model which is defined as shown which is acted upon a query and gets a list of objects that have to placed in appropriate cells of a table. Here is the relevant part of the code.

class Location(models.Model):
    x=models.IntegerField(null=True)
    y=models.IntegerField(null=True)
    z=models.CharField(max_length=5,null=True)

    def __unicode__(self):
        return self.z

From this db i want retrieve all the objects and place them in a 2d-table with row and column defined by x,y of that object.If there is no object for certain (x,y) then that particular slot should be shown empty in the table.This is the view I wrote to meet those ends.

def gettable(request):
    events=[]
    for xdim in xrange(3):
        xe=[]
        for ydim in xrange(3):
            object=[0]
            object.append(Location.objects.filter(x=xdim,y=ydim))
            xe.append(object[-1])
            events.append(xe)
    return render(request, 'scheduler/table.html', {'events':events})

Here is the html part of the code

<table border="1">
    <th>Header 0</th>
    <th>Header 1</th>
    <th>Header 2</th>
    {% for event in events %}
    <tr>
    {% for x in event %} <td>{{ x }}</td>
    {% endfor %}
    </tr>
    {% endfor %}
</table>

I have to tackle multiple issues here.

1.My code for views is not at all elegant (which is bad since I know django offers lots of stuff to tackle such tasks) as I am defining variables specifically to loop through instead of taking those from the (x,y) values of database objects.

2.I get output in [<Location: 21>] format but I want it as '21'.

3.How do I introduce empty cells where there doesnot exist any object for given (x,y).

4.Please suggest any other way possible which can make my code simpler and general.

1
6
2/9/2012 11:24:15 AM

Accepted Answer

If you want to make your code simpler, I would like to recommend to use application django-tables2. This approach can solve all your issues about generating tables.

As documentation sais:

django-tables2 simplifies the task of turning sets of data into HTML tables. It has native support for pagination and sorting. It does for HTML tables what django.forms does for HTML forms. e.g.

Its features include:

  • Any iterable can be a data-source, but special support for Django querysets is included.
  • The builtin UI does not rely on JavaScript.
  • Support for automatic table generation based on a Django model.
  • Supports custom column functionality via subclassing.
  • Pagination.
  • Column based table sorting.
  • Template tag to enable trivial rendering to HTML.
  • Generic view mixin for use in Django 1.3.

Creating a table is as simple as:

import django_tables2 as tables

class SimpleTable(tables.Table):
    class Meta:
        model = Simple 

This would then be used in a view:

def simple_list(request):
    queryset = Simple.objects.all()
    table = SimpleTable(queryset)
    return render_to_response("simple_list.html", {"table": table},
                              context_instance=RequestContext(request))

And finally in the template:

{% load django_tables2 %} 
{% render_table table %}

This example shows one of the simplest cases, but django-tables2 can do a lot more! Check out the documentation for more details.

It is also possible to use dictionary instead of queryset.

17
2/12/2012 7:49:41 AM

For point 2, you're giving each cell a list rather than a single object, {{ x.0 }} should give you the right value, but it also suggests you're approaching it wrong in your view logic.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon