Django: customizing the message after a successful form save

前端 未结 2 1637
深忆病人
深忆病人 2021-01-18 20:36

whenever I save a model in my Admin interface, it displays the usual \"successfully saved message.\" However, I want to know if it\'s possible to customize this message bec

2条回答
  •  粉色の甜心
    2021-01-18 21:12

    Django (> version 1.2) uses the messages framework for admin messages. You can add additional messages using that interface. Here's an example:

    from django.contrib import messages
    
    class SomeModelAdmin(admin.ModelAdmin):
        # your normal ModelAdmin stuff goes here
    
        def save_model(self, request, obj, form, change):
            # add an additional message
            messages.info(request, "Extra message here.")
            super(SomeModelAdmin, self).save_model(request, obj, form, change)
    

    To detect changes to the object being saved, you should be to override the save_model method of ModelAdmin, and compare the object the method is passed to the version currently in the database. To do this in the case of inlines, you can override the save_formset method. A possible approach might look like (untested code):

    class SomeModelAdmin(admin.ModelAdmin):
        # your normal ModelAdmin stuff goes here
    
        def save_formset(self, request, form, formset, change):
            if not change:
                formset.save()
            else:
                instances = formset.save(commit=False)
    
                for instance in instances:
                    try:
                        # if you've got multiple types of inlines
                        # make sure your fetching from the 
                        # appropriate model type here
                        old_object = SomeOtherModel.get(id=instance.id)
                    except SomeOtherModel.DoesNotExist:
                        continue
    
                    if instance.field_x != old_object.field_x:
                        messages.info(request, "Something Changed")
    
                instance.save()
    
            formset.save_m2m()
    

提交回复
热议问题