I\'m using the standard django admin module to display a list of rows. One of the columns is a numerical field. I\'d like to display an extra \'totals\' row that has most of
I think the Django way to do this is to override the ChangeList class which django's admin app uses. You do this in django 1.2 by calling the get_changelist
method in your admin class. In my example: TomatoAdmin
calls this method returning a custom ChangeList calss. This ChangeList class: MyChangeList
simply adds an extra attribute to the context of change_list.html
.
Make sure that change_list.html is in the following directory:
app_label/change_list.html
in the example this is: templates/admin/tomato/change_list.html
models.py (A simple model with an integer field)
class CherryTomato(models.Model):
name = models.CharField(max_length=100)
num_in_box = models.IntegerField()
admin.py (your Admin class and a custom ChangeList class)
from django.contrib import admin
from django.contrib.admin.views.main import ChangeList
from django.db.models import Count, Sum
from tomatoes.tomato.models import CherryTomato
class MyChangeList(ChangeList):
def get_results(self, *args, **kwargs):
super(MyChangeList, self).get_results(*args, **kwargs)
q = self.result_list.aggregate(tomato_sum=Sum('num_in_box'))
self.tomato_count = q['tomato_sum']
class TomatoAdmin(admin.ModelAdmin):
def get_changelist(self, request):
return MyChangeList
class Meta:
model = CherryTomato
list_display = ('name', 'num_in_box')
admin.site.register(CherryTomato, TomatoAdmin)
change_list.html (relevant bit only, copy/paste the existing one and extend it)
{% block result_list %}
{% if action_form and actions_on_top and cl.full_result_count %}{% admin_actions %}{% endif %}
{% result_list cl %}
{% if action_form and actions_on_bottom and cl.full_result_count %}{% admin_actions %}{% endif %}
Tomatoes on this page: {{ cl.tomato_count }}
{% endblock %}
I'll leave it up to you how to style this the way you want it.