Django:如何覆盖form.save()? [英] Django: How to override form.save()?
问题描述
MultipleChoiceField
w / a修改的 CheckboxSelectMultiple
。 / p> 现在我需要将这些数据保存回数据库。即,我需要将单个窗口小部件返回的数据拆分成多个布尔列。我认为这适用于 save()
方法,否?
问题是,我该怎么办?这样的东西?
def save(self,commit = True):
#code here
return超级(MyForm,self).save(commit)
如果是... 我设置了值?
self.fields ['my_field']。value ='my_flag'in self。 clean_data ['multi_choice']
还是什么? 所有数据存储在哪里?
您希望存储数据的地方是新的模型实例:
def save(self,commit = True):
instance = super(MyForm,self) save(commit = False)
instance.flag1 = self.cleaned_data中的'flag1'['multi_choice']#etc
如果提交:
instance.save()
返回实例
My model has quite a few boolean fields. I've broken these up into 3 sets which I'm rendering as a MultipleChoiceField
w/ a modified CheckboxSelectMultiple
.
Now I need to save this data back to the DB. i.e., I need to split the data returned by a single widget into multiple boolean columns. I think this is appropriate for the save()
method, no?
Question is, how do I do I do it? Something like this?
def save(self, commit=True):
# code here
return super(MyForm, self).save(commit)
If so... how do I set the values?
self.fields['my_field'].value = 'my_flag' in self.cleaned_data['multi_choice']
Or something? Where's all the data stored?
The place you want your data to be stored is your new model instance:
def save(self, commit=True):
instance = super(MyForm, self).save(commit=False)
instance.flag1 = 'flag1' in self.cleaned_data['multi_choice'] # etc
if commit:
instance.save()
return instance
这篇关于Django:如何覆盖form.save()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!