Django: How to override form.save()?

自古美人都是妖i 提交于 2019-12-17 15:32:09

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/3927305/django-how-to-override-form-save

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!