Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to render a Queryset into a table template-django

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.

like image 986
Kamal Reddy Avatar asked Feb 09 '12 06:02

Kamal Reddy


People also ask

How do I append QuerySet in Django?

Use union operator for queryset | to take union of two queryset. If both queryset belongs to same model / single model than it is possible to combine querysets by using union operator. One other way to achieve combine operation between two queryset is to use itertools chain function.

How do I cut a QuerySet in Django?

Slicing. As explained in Limiting QuerySets, a QuerySet can be sliced, using Python's array-slicing syntax. Slicing an unevaluated QuerySet usually returns another unevaluated QuerySet , but Django will execute the database query if you use the “step” parameter of slice syntax, and will return a list.

Is Django QuerySet lazy?

This is because a Django QuerySet is a lazy object. It contains all of the information it needs to populate itself from the database, but will not actually do so until the information is needed.

How does QuerySet work in Django?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.

What is a template in Django?

A Django template is a text document or a Python string marked-up using the Django template language. Some constructs are recognized and interpreted by the template engine. The main ones are variables and tags. A template is rendered with a context.

How to modify Dataframe for Table View in Django?

In Django, It is easy to render the HTML templates by setting URLs of respective HTML pages. Here we will let to know about how we can work with DataFrame to modify them for table view in the HTML template or web-pages, and for that, we have to use ‘render’ and ‘HttpResponse’ functions to manipulate the data inside the DataFrame.

How to use Django-specific APIs in Jinja2 templates?

In order to use Django-specific APIs, you must configure them into the environment. For example, you can create myproject/jinja2.py with this content: and set the 'environment' option to 'myproject.jinja2.environment'. Then you could use the following constructs in Jinja2 templates:

How to generate HTML dynamically in Django?

Being a web framework, Django needs a convenient way to generate HTML dynamically. The most common approach relies on templates. A template contains the static parts of the desired HTML output as well as some special syntax describing how dynamic content will be inserted. For a hands-on example of creating HTML pages with templates, see Tutorial 3.


2 Answers

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.

like image 147
ramusus Avatar answered Sep 30 '22 13:09

ramusus


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

like image 23
Laur Ivan Avatar answered Sep 30 '22 13:09

Laur Ivan