Django: Method to execute after "clean" in admin

Viewed 103

Fairly simple: Which method can be overwritten after "clean" method? I am using "clean" to verify an uploaded image and once I confirmed it is ok and saved, I want to switch it using some external API:

class FooAdminForm(forms.ModelForm):
    class Meta:
        model = Asset
        fields = ["name", "file",]
    
    def clean(self):
        cleaned_data = super(FooAdminForm, self).clean()
        ...
        return cleaned_data

    def bar(self):
        # do stuff with new data in database


class FooAdmin(admin.ModelAdmin):
    list_display = ["name", "file",]
    form = FooAdminForm

is there some method bar that can do what I need? Or do I have to wrestle with a signal (like here)?

1 Answers

The ModelAdmin class has a method save_model [Django docs] which is called to save the model instance, so you can override that if needed:

class FooAdmin(admin.ModelAdmin):
    list_display = ["name", "file",]
    form = FooAdminForm
    
    def save_model(self, request, obj, form, change):
        super().save_model(request, obj, form, change)
        # Do something with `obj`
Related