Django: customizing the message after a successful form save

被刻印的时光 ゝ 提交于 2019-12-19 19:52:53

问题


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 because I have a situation where I want to warn the user about what he just saved and the implications of these actions.

class PlanInlineFormset(forms.models.BaseInlineFormset):
    def clean(self):
        ### How can I detect the changes?  
        ### (self.changed_data doesn't work because it's an inline)
        ### and display what he/she just changed at the top AFTER the successful save?

class PlanInline(admin.TabularInline):
    model = Plan
    formset = PlanInlineFormset

回答1:


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()



回答2:


If you're using Django 1.2 or newer, the messages framework may hold the answer.

http://docs.djangoproject.com/en/dev/ref/contrib/messages/



来源:https://stackoverflow.com/questions/4548325/django-customizing-the-message-after-a-successful-form-save

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!