﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
13950	"Add ""post save"" hook to ModelAdmin class"	3point2	pandres	"If a model with a set of related objects is edited in the admin, there is currently no way to run any code once the admin site has saved the related objects.

For example, consider an invoice:

models.py:

{{{
class Invoice(models.Model):
    # fields like customer_name, etc
    total = models.DecimalField(max_digits=11, decimal_places=2)

    def update_total(self):
        self.total = sum([x.cost for x in self.invoiceentry_set.all()]

class InvoiceEntry(models.Model):
    invoice = models.ForeignKey(Invoice)
    item = models.CharField(max_length=100)
    cost = models.DecimalField(max_digits=11, decimal_places=2)
    # etc
}}}

When clicking ""save"" in the admin after editing or adding an invoice in the admin interface, there is no way to have the invoice update its total using the update_total method. Overriding the save() method on the Invoice model doesn't help, because it is called before the related !InvoiceEntries are created and saved.

I supposes the functionality I want could be implemented by overriding the save() method for the !InvoiceEntry model and have it update the total of the parent instance, although this seems a little inelegant as the Invoice instance would then be updated and saved once for every invoice entry created or edited.

I suggest adding a ""post_save"" option to the !ModelAdmin class, which will be called once all related objects have been saved. Please consider the attached patch. It allows the following:

admin.py:

{{{
class InvoiceAdmin(admin.ModelAdmin):
    def post_save(self, instance):
        instance.update_total()

admin.site.register(Invoice, InvoiceAdmin)
}}}

With the patch, the post_save method above is called after the invoice and all its related entries have been created and saved.

If this is considered for inclusion into Django, I'd be happy to modify the patch to include documentation.

Vasili"	Uncategorized	closed	contrib.admin	1.2	Normal	wontfix			Unreviewed	1	1	1	1	0	0
