#13950: Add "post save" hook to ModelAdmin class
----------------------------------+-----------------------------------------
 Reporter:  3point2               |       Owner:  nobody    
   Status:  new                   |   Milestone:            
Component:  django.contrib.admin  |     Version:  1.2       
 Keywords:                        |       Stage:  Unreviewed
Has_patch:  1                     |  
----------------------------------+-----------------------------------------
 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

-- 
Ticket URL: <http://code.djangoproject.com/ticket/13950>
Django <http://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/django-updates?hl=en.

Reply via email to