5

每当我在管理界面中保存模型时,它都会显示通常的“成功保存的消息”。但是,我想知道是否可以自定义此消息,因为我有一种情况,我想警告用户他刚刚保存的内容以及这些操作的含义。

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
4

2 回答 2

8

Django(> 1.2 版)使用消息框架来处理管理消息。您可以使用该界面添加其他消息。这是一个例子:

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)

要检测正在保存的对象的更改,您应该覆盖 ModelAdmin 的save_model 方法,并将该方法传递的对象与数据库中当前的版本进行比较。要在内联的情况下执行此操作,您可以覆盖save_formset 方法。一种可能的方法可能看起来像(未经测试的代码):

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()
于 2010-12-29T07:26:29.363 回答
1

如果您使用的是 Django 1.2 或更新版本,消息框架可能会提供答案。

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

于 2010-12-29T03:11:43.253 回答