我想要样本标记,用于显示任何模型数组的表格,如:
{% table city_list %}
有人看到这样的东西吗?
答案 0 :(得分:1)
您可以尝试使用django-tables app,它允许您执行以下操作,具体型号为:
# 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%}
答案 1 :(得分:0)
答案 2 :(得分:0)
我做了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 %}