Igor Golodnitsky
Igor Golodnitsky

Reputation: 4566

Django template tag for Model query result

I wonna simple tag, for showing table of any model arrays like:

{% table city_list %}

Do anybody see such things?

Upvotes: 0

Views: 1945

Answers (3)

bradley.ayers
bradley.ayers

Reputation: 38392

I've made a fork of django-tables which makes this extremely easy. Here's a simple example:

In models.py:

from django.db import models

class City(models.Model):
    name = models.CharField(max_length=200)
    state = models.CharField(max_length=200)
    country = models.CharField(max_length=200)

In tables.py:

import django_tables as tables
from .models import City

class CityTable(tables.Table):
    class Meta:
        model = City

In views.py:

from django.shortcuts import render_to_response
from django.template import RequestContext
from .models import City
from .tables import CityTable

def city_list(request):
    queryset = City.objects.all()
    table = CityTable(queryset)
    return render_to_response("city_list.html", {"city_table": table},
                              context_instance=RequestContext(request))

In city_list.html:

{% load django_tables %}
{% render_table city_table %}

Upvotes: 0

gamesbook
gamesbook

Reputation: 29

Try generic vieww e.g. http://www.djangobook.com/en/2.0/chapter11/

Upvotes: 0

Andriy Drozdyuk
Andriy Drozdyuk

Reputation: 61121

You can try django-tables app, which allows you to do the following, given model Book:

# Define 
class BookTable(tables.ModelTable):  
  id = tables.Column(sortable=False, visible=False)  
  book_name = tables.Column(name='title')  
  author = tables.Column(data='author__name')  
  class Meta:  
      model = Book  

# In your views
initial_queryset = Book.objects.all()  
books = BookTable(initial_queryset)
return render_to_response('table.html', {'table': books})  


# In your template table.html
<table>  

<!-- Table header -->
<tr>  
   {% for column in table.columns %}  
   <th>{{ column }}</th>
   {% endfor %}
</tr>  

<!-- Table rows -->
{% for row in table.rows %}
<tr>
   {% for value in row %}
   <td>{{ value }}</td>
   {% endfor %}
</tr>
{% endfor %}

 </table>  

I think the above is much more elegant and self explanatory than just doing {% table book_list %}

Upvotes: 1

Related Questions