Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alter fields in Django formset using clean

How do you alter fields in each form of a Django formset using the clean method?

class MyInlineFormSet(BaseInlineFormSet):

    def clean(self):
        if self.cleaned_data['inputted'] == self.cleaned_data['answer']:
            self.cleaned_data['is_correct'] = True
        return self.cleaned_data

This isn't working and I've seen people iterate over each form but they only validate and not alter. If I iterate over each form how do I then return the cleaned_data? In other words:

class MyInlineFormSet(BaseInlineFormSet):

    def clean(self):    
        for form in self.forms:
            if form.cleaned_data['inputted'] == form.cleaned_data['answer']:
                form.cleaned_data['is_correct'] = True
        ...?
like image 820
ssomnoremac Avatar asked Apr 20 '26 03:04

ssomnoremac


1 Answers

Based on ssomnoremac comment, I used form.instance.field_i_wanted_to_change in the BaseModelFormSet clean method instead of form.cleaned_data['field_i_wanted_to_change'] and it worked. Something like

class MyInlineFormSet(BaseInlineFormSet):

def clean(self):
    for form in self.forms:
        if form.cleaned_data['inputted'] == form.cleaned_data['answer']:
            form.instance.is_correct = True

In my case, I had already called clean_field_i_wanted_to_change, so the order is clean_field > clean @ MyInlineFormSet Django 1.11

like image 99
Raphael Fernandes Avatar answered Apr 21 '26 15:04

Raphael Fernandes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!