gpt4 book ai didi

Django:在成功保存表单后自定义消息

转载 作者:行者123 更新时间:2023-12-04 17:40:47 26 4
gpt4 key购买 nike

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

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

最佳答案

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)

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

关于Django:在成功保存表单后自定义消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4548325/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com