[Answer]-Django model override save function not updating m2m field in db

1👍

If you have the keywords field in your admin form what happens is this:

  1. you press save on your new Banners instance in the admin (with no keywords selected)
  2. Django admin model-form saves the Banners instance
  3. your overridden save method adds your keywords
  4. Django admin sets the keywords m2m field to whatever keywords were submitted in the form (replacing what you set in the save method)

The reason Django does this is because, as you know, the Banners instance has to be saved before m2m relations can be added.

I have been round in circles with this myself in the past messing with m2m_changed signal etc… but you’re likely to end up with something that only works in narrow set of circumstances in the Django admin site, but doesn’t make sense in other code.

Your save method is working I think (try it in a console, outside Django admin), what you really need is to customise behaviour of the admin form:

class BannersForm(forms.ModelForm):
    class Meta:
        model = Banners

    def __init__(self, *args, **kwargs):
        if kwargs.get('instance') is None:
            # create new Banners
            initial = kwargs.get('initial', {})
            initial.update({'keywords': Keywords.objects.filter(pk=1)})
            kwargs['initial'] = initial
        super(BannersForm, self).__init__(*args, **kwargs)


class BannersAdmin(admin.ModelAdmin):
    form = BannersForm


admin.site.register(Banners, BannersAdmin)

Leave a comment