gpt4 book ai didi

Django FormView : distinguishing between create and update

转载 作者:行者123 更新时间:2023-12-03 22:50:29 26 4
gpt4 key购买 nike

我有一个自定义 FormView 类的 mixin,如果保存成功,它只会添加一条成功消息,所以:

class MessagesMixin(object):

def form_valid(self, form):
response = super(MessagesMixin, self).form_valid(form)
messages.add_message(self.request,
messages.SUCCESS,
'Successfully created %s' % form.instance)
return response

如您所见,这仅真正涵盖了创作。如果实例已更新,消息仍将显示“已创建”。有没有办法区分 form_valid 方法中的创建/更新?

最佳答案

一种解决方案是在你的 mixin 中添加一个属性,然后在你的 Update 中设置它。和 Create意见。您可以定义静态属性或重载 get_form_valid_msg如果你需要一些动态的东西。未经测试的代码:

from django.core.exceptions import ImproperlyConfigured

class MessagesMixin(object):
@property
def form_valid_msg(self):
raise ImproperlyConfigured("you're missing the 'form_valid_msg' property")

def get_form_valid_msg(self):
return self.form_valid_msg

def form_valid(self, form):
response = super(MessagesMixin, self).form_valid(form)

msg = 'Successfully {form_valid_msg} {form}'.format(
form_valid_msg=self.get_form_valid_msg(),
form=form.instance
)

messages.success(self.request, msg)

return response

关于Django FormView : distinguishing between create and update,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17766056/

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