Django: How to override form.save()?

DjangoDjango Forms

Django Problem Overview


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?

Django Solutions


Solution 1 - Django

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmpenView Question on Stackoverflow
Solution 1 - DjangoWoganView Answer on Stackoverflow