how to render a Queryset into a table template-django

27,828

Solution 1

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 the documentation says:

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 a dictionary instead of a queryset.

Solution 2

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.

Solution 3

Per point:

  1. IMO you can get away with creating a custom filter or a tag and using the queryset.
  2. You need to define a __unicode__ (or __string__) method to return your desired item.
  3. If the value is empty or the item doesn't exist, the rendered result will be empty too.

HTH

Share:
27,828
Kamal Reddy
Author by

Kamal Reddy

console.log('I am Awesome'); You can donate here(Bitcoin address): 1JWhS3ebNnBpVE2vGXdR8q6igFuoKfMkpC

Updated on September 08, 2021

Comments

  • Kamal Reddy
    Kamal Reddy over 2 years

    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.

  • Nan
    Nan over 4 years
    render is now simpler: return render(request, 'simple_list.html', {"table": table})