我想要一个简单的标签,用来显示任何模型数组的表,比如:
{% table city_list %}有没有人看到过这样的东西?
发布于 2009-11-07 02:39:09
你可以尝试django-tables应用,它允许你在给定模型书的情况下执行以下操作:
# 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> 我认为上面的代码比只做{% table book_list %}要优雅得多,也不言自明
发布于 2010-06-17 23:20:16
尝试通用视图,例如http://www.djangobook.com/en/2.0/chapter11/
发布于 2011-06-08 15:26:46
我已经做了一个fork of django-tables,它让这件事变得非常简单。下面是一个简单的例子:
在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)在tables.py中
import django_tables as tables
from .models import City
class CityTable(tables.Table):
class Meta:
model = City在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))在city_list.html中
{% load django_tables %}
{% render_table city_table %}https://stackoverflow.com/questions/1044421
复制相似问题