Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

python - django-admin: Add extra row with totals

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 the columns as blank, except for the numerical column, which should be the total for all of the objects.

Is there a simple way to do this within the admin module, or am I better off making a custom view for it?

I'm using Django 1.2.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, you can do it in many ways, but most django-ist way to do is:

First override the default django listing view... And give a new template file directory

ModelAdmin.changelist_view(self, request, extra_context=None)

Like:

class MyModelAdmin(admin.ModelAdmin):

    # A template for a very customized change view:
    change_list_template = 'admin/myapp/extras/sometemplate_change_form.html'

    def get_total(self):
        #functions to calculate whatever you want...
        total = YourModel.objects.all().aggregate(tot=Sum('total'))['tot']
        return total

    def changelist_view(self, request, extra_context=None):
        my_context = {
            'total': self.get_total(),
        }
        return super(MyModelAdmin, self).changelist_view(request,
            extra_context=my_context)

So, you add your list view context a 'total' that keeps your total value and pass it to the template.

if change_list_template will set, django uses that template, otherwise, it uses standard django template.

If def changelist_view(self, request, extra_context=None) is called, django uses that function to create the content, otherwise it uses default django views.

Then create a admin/myapp/extras/sometemplate_change_form.html file and place your {{total}} to any place you want.

A guide to how to override admin templates And here is how to override admin views

UPDATE: I add a simple aggregate to calculate total. you can edit it to set it as your needs.

UPDATE 2: ModelAdmin template override option fixed from ModelAdmin.change_form_template to ModelAdmin.change_list_template. (thank you c4urself). Yes, but changing the default django admin template is a really bad choice, since it is used by many other ModelAdmin's and it might cause problems if related templates are updated.



NB:
The Total doesn't change when using filters, see comment below.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...