如何重写 modelform 类的 save() 方法并添加缺失的信息?
我刚开始学习Django,我有一个问题。
我试图在保存表单数据时自动添加缺少的信息。我可以通过重写 modelform 类的 save() 方法来更改/添加所需的“cleaned_data”信息,但更改不会记录在数据库中。其实修改后的信息怎么写呢?这是代码:
def save(self, commit = True, *args, **kwargs):
temp = ServiceMethods(url = self.cleaned_data.get('url'), wsdl_url = self.cleaned_data.get('wsdl_url'))
if not temp.get_wsdl_url():
temp.make_wsdl_url()
if temp.get_wsdl_url():
temp.make_wsdl()
self.cleaned_data['wsdl_url'] = temp.get_wsdl_url()
self.cleaned_data['wsdl_description'] = temp.get_wsdl_description()
super(ServiceForm, self).save(commit = commit, *args, **kwargs)
型号:
class Services(models.Model):
name = models.CharField('Имя', max_length=256)
url = models.URLField('Ссылка', unique = True)
wsdl_url = models.URLField('Ссылка на WSDL-документ', blank=True)
description = models.TextField('Описание сервиса',blank=True)
wsdl_description = models.TextField('WSDL описание', blank=True, editable=False)
added = models.DateTimeField('Добавлено', auto_now_add=True)
TIA
I just started to learn Django and I had a question.
I'm trying to automatically add the missing information, when saving form data. I get to change/add the desired "cleaned_data" information by overriding save() method of modelform class, but changes are not recorded in the database. Actually, how to write the modified information? This is code:
def save(self, commit = True, *args, **kwargs):
temp = ServiceMethods(url = self.cleaned_data.get('url'), wsdl_url = self.cleaned_data.get('wsdl_url'))
if not temp.get_wsdl_url():
temp.make_wsdl_url()
if temp.get_wsdl_url():
temp.make_wsdl()
self.cleaned_data['wsdl_url'] = temp.get_wsdl_url()
self.cleaned_data['wsdl_description'] = temp.get_wsdl_description()
super(ServiceForm, self).save(commit = commit, *args, **kwargs)
And model:
class Services(models.Model):
name = models.CharField('Имя', max_length=256)
url = models.URLField('Ссылка', unique = True)
wsdl_url = models.URLField('Ссылка на WSDL-документ', blank=True)
description = models.TextField('Описание сервиса',blank=True)
wsdl_description = models.TextField('WSDL описание', blank=True, editable=False)
added = models.DateTimeField('Добавлено', auto_now_add=True)
TIA
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试在
self.instance
上设置数据,而不是在self.cleaned_data
中,并让我知道这是否有效。Try setting the data on
self.instance
instead of inself.cleaned_data
, and let me know if that works.