[Answer]-Django manytomany field in admin โ€“ how to add a default list?

1๐Ÿ‘

โœ…

You can override the Admin Form and implement the logic in the form clean method for your ManyToMany field. For eg.

def clean_recipients(self):
    data = self.cleaned_data['recipients']

    if not data:
        # return default recipients if the selected list is empty.
        data =  [r.pk for r in Recipient.objets.all()]  #just an example, you can alter this query to select your defaults

    return data

Update

Override the save method to save recepients

def save(self, commit=True):
    instance = forms.ModelForm.save(self, False)

    old_save_m2m = self.save_m2m
    def save_m2m():
       old_save_m2m()
       instance.recepient_set.clear()
       for recepient in self.cleaned_data['recepients']:
           instance.recepient_set.add(recepient)
    self.save_m2m = save_m2m

    if commit:
        instance.save()
        self.save_m2m()

    return instance
๐Ÿ‘คAmit

0๐Ÿ‘

This is a snippet of code I used to auto populate an author in an admin formset if it was not set

class AutoAuthoredModelAdmin(admin.ModelAdmin):

    def save_model(self, request, obj, form, change):
        if obj.author is None: 
            obj.author = request.user
        super(AutoAuthoredModelAdmin, self).save_model(request, obj, form, change)

    def save_formset(self, request, form, formset, change): 
        if hasattr(formset.model, 'author'):
            instances = formset.save(commit=False)
            for instance in instances:
                if instance.author is None:
                    instance.author = request.user
        super(AutoAuthoredModelAdmin, self).save_formset(request, form, formset, change)
๐Ÿ‘คSteve K

Leave a comment