Hooks for m2m-fields and inline formsets in Django newforms

So,

it seems many people, like myself, come across a situation where they when saving an instance want to do some action based on related objects. And most likely they soon find out that the related objects haven’t been updated or saved by the time the save method is called. The Django ORM gives no such guarantee, and I can see why it’s made that way. What I think could be done is letting the form processing notify you when many-to-many and inline formsets have been processed.

So I installed the newforms-admin branch and started digging around. The attached patch is what I came up with.

I basically customized form_change, form_add in ModelAdmin and formset_add, formset_change in InlineModelAdmin to pass along the methods post_m2m and post_formset if they are defined in the class.
These are then passed on to the form creation and in the end get called when ManyToManyFields have been updated (post_m2m) or when inline objects in a formset has been updated (post_formset).

Most changes, except those to save_instance in newforms/models.py can easily be broken out and made in sub-classes or new functions instead but I decided to share a version where I patched the code directly since that’s what I started out doing.

Some random code just to show the concept:


class PackageOptionInline(admin.TabularInline):
    model = PackageOption
    extra = 2

    def post_m2m(self,obj):
         print "in packageoption form post_m2m"

    def post_formset(self,objs):
         print "in packageoption form post_formset",objs
         if objs:
              objs[0].packageconfig.create_packages()

class ContactOptions(admin.ModelAdmin):

      def post_m2m(self,obj):
            """in form post_m2m
            perhaps update something
            based on contact categories
            or something else.."""
            obj.dosomething()

I hope you get the idea. Let me know if you think I’m missing something.

Tags: , ,

One Response to “Hooks for m2m-fields and inline formsets in Django newforms”

  1. dillondean15224 Says:

    uc4f8uc4f8ud55c ubd84uc704uae30uac00 uc660uc9c0 uc88buc9c0 uc54aub098uc694? Click http://tu2s.in/pookme100830

Leave a comment