Python 如何在条件满足时强制保存_模型以使其失败(Django)
即使在显示错误消息且未保存对象时,save_model方法也会说: 已成功添加真实状态“RealState对象” 管理员Python 如何在条件满足时强制保存_模型以使其失败(Django),python,django,django-admin,Python,Django,Django Admin,即使在显示错误消息且未保存对象时,save_model方法也会说: 已成功添加真实状态“RealState对象” 管理员 class RealStateAdmin(admin.ModelAdmin): model = RealState can_delete = False list_display = ['name', 'country', 'state', 'city', 'acquisition_date', 'acquisition_value'] inl
class RealStateAdmin(admin.ModelAdmin):
model = RealState
can_delete = False
list_display = ['name', 'country', 'state', 'city', 'acquisition_date', 'acquisition_value']
inlines = [Inlines.CurrentValueRealStateAdminInline]
def save_model(self, request, model, form, change):
model.owner = Owner.objects.get(user_id=request.user.id)
ca = CheckingAccount.objects.get(owner_id=model.owner_id)
if(model.acquisition_value <= ca.balance):
if(model.rental_value ==""):
model.rental_value = None
super(RealStateAdmin, self).save_model(request, model, form, change)
else:
messages.error(request, "Insufficient funds in your checking account to make this transaction.");
类RealStateAdmin(admin.ModelAdmin):
模型=真实状态
can_delete=False
列表显示=[“名称”、“国家”、“州”、“城市”、“采集日期”、“采集值”]
inlines=[inlines.CurrentValueRealStateAdminline]
def保存模式(自我、请求、模式、表单、更改):
model.owner=owner.objects.get(user\u id=request.user.id)
ca=CheckingAccount.objects.get(所有者id=model.所有者id)
如果(model.acquisition_)值未保存(预期行为)。
但save_模式的绿色信息仍在出现。
有什么想法吗?这些消息是在ModelAdmin中添加的。如果您不想要消息,最简单的方法是按照消息中的说明关闭它们
您可以从已安装的应用程序中删除“django.contrib.messages”
来自中间件类的MessageMiddleware行,以及消息
来自模板的上下文处理器
如果希望消息显示在其他位置,只需在save\u model
方法中清除消息即可
存储实例启动时,这些消息被标记为清除
迭代(并在处理响应时清除)
与以前相同的引用。显示错误消息的正确方法是
self.message_user(request,
"Insufficient funds in your checking account to make this transaction.",
messages.SUCCESS)
如果我没有正确地使用你的代码,那么在clean方法中检查此项并引发validationError如何?因为django的消息是在form之后发送的。我认为它是有效的,我认为它还不错。但是我正在尝试获取表单失败。我的意思是,如果我在save_模型中进行的验证没有通过,请将消息提供给用户并让他们进入表单。我的swer为您提供了这一功能。如果您希望验证失败,您需要一个自定义管理表单。您的解决方案(带有我的添加:)更简单
self.message_user(request,
"Insufficient funds in your checking account to make this transaction.",
messages.SUCCESS)