RS7
RS7

Reputation: 2361

Django Forms - set field as blank if field contains errors

In a form, I'd like to have certain fields that are set as blank if they contain any validation errors. For example, if I have a decimal field called price and it has an invalid value of blue, I'd like just silently set the field to none.

This would be used to make search filters via query strings so if there is a better solution, please let me know.

Edit 2

class SearchForm(forms.Form):
    q = forms.CharField()
    price = forms.DecimalField(required=False)

I'd like the form to be able to handle invalid field values in a way that the form does not become invalid. For example, if I have ?q=car&price=100 the form would work. If I have ?q=car&price=circle, I'd like the form to notice the error (value isn't a decimal) but instead of making the form invalid, just make the field blank.

The clean_* would be useful for validating non field type specific errors, yes? (Field type related errors would have already been checked and invalidated the form). If so, how should I go about detecting these errors?

My approach could be totally wrong here - I'm basically trying to create search filters.

Upvotes: 1

Views: 202

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599788

That's exactly what the clean_field method is for. So for example in your example:

class MyForm(forms.Form):
    ...
    def clean_price(self):
        value = self.cleaned_data['price']
        if value == 'blue':
            value = ''
        return value

Upvotes: 1

Related Questions