Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django clean_field that references other fields

I have a situation where a user can click a check box field, "field_enable", on an html form and a nice jQuery operation will display another field, "fielda", for the user to enter more data in. When "field_enable" is checked, I want to require the user to also fill out "fielda". When "field_enable" is unchecked, the user should be allowed to submit the form without an error.

I want all of the errors to appear in the error list above the field rather than the form.errors list for the overall form (that's why I'm not using the form's clean() method). Therefore, I came up with this code below.

The enable/disable logic works great. When the "field_enable" is checked, the user must fill out "fielda" and when it is unchecked, the user passes along. However, when the box is checked, requiring the user to fill out more information, even if they fill in a value for "fielda" they sill get the validation error "Fielda is required". This defies expectation.

Does anyone have any advice as to why "fielda" always fails validation whenever "field_enable" is checked

class MyForm(forms.ModelForm):

    def clean_fielda(self):
        cleaned_data = self.cleaned_data
        if cleaned_data.get("field_enable"):
            raise forms.ValidationError("Fielda is required")
        return cleaned_data['fielda']

An example of the model

class MyModel(models.Model):
    field_enable = models.BooleanField(default=False)
    fielda = models.CharField(max_length=128, blank=True, null=True)

Any help is much appreciated!

Joe

like image 762
Joe J Avatar asked Jul 31 '10 00:07

Joe J


1 Answers

You want to raise a validation error if "field_enable" was checked and that you don't have a value for 'field_a'. Like so (you're missing the "field_a" exists check):

class MyForm(forms.ModelForm):

    def clean_fielda(self):
        cleaned_data = self.cleaned_data
        if cleaned_data.get("field_enable") and not cleaned_data.get('field_a'):
            raise forms.ValidationError("Fielda is required")
        return cleaned_data['fielda']
like image 133
Sam Dolan Avatar answered Oct 16 '22 18:10

Sam Dolan