nknj
nknj

Reputation: 2486

Custom cleaning form data in django

I know how to clean data in django's forms.py but I am running into a weird error which i have never encountered before

I have this is my forms.py:

class BetaPhoneForm(ModelForm):
class Meta:
    model = RegisterHotTable
    fields = ('pracPhone',)

def clean_pracPhone(self):
    pracPhone = self.cleaned_data['pracPhone']

    if pracPhone is None:
        raise forms.ValidationError("This value cannot be empty")
    else:
        if not pracPhone.isdigit():
            raise forms.ValidationError("Please enter a valid phone number.")
    return pracPhone

So i am cleaning my field with the custom clean method, clean_pracPhone. It works for the part when i leave the value blank and see "This value cannot be empty"

I want the form to display the error "Please enter a valid phone number." instead of the standard "Enter a whole number" when i enter alphabets instead of numbers.

In fact, i realised that this method is not even run when I enter alphabets.

I know i can 'hack' around this by creating a custom charfield and not use the ModelForm but i dont really want to do that.

I also tried self.data instead of self.cleaned_data but it did not work.

Any ideas how I can get this to work.

Thanks!

Upvotes: 2

Views: 5888

Answers (1)

Derek Kwok
Derek Kwok

Reputation: 13078

Based on your error message, I am assuming pracPhone is represented by anmodels.IntegerField in your models. This means that in your ModelForm, the field is represented by forms.IntegerField.

forms.IntegerField come with some validations by default:

  • required
  • invalid
  • min_value
  • max_value

You should override the default messages for the validation on an IntegerField instead.

class BetaPhoneForm(forms.ModelForm):

    pracPhone = forms.IntegerField(error_messages={
        "required": "This value cannot be empty.",
        "invalid": "Please enter a valid phone number.",
    })

    class Meta:
        model = RegisterHotTable
        fields = ('pracPhone',)

    def clean_procPhone(self):
        pracPhone = self.cleaned_data['pracPhone']
        # your other validations go here.
        return pracPhone

Upvotes: 4

Related Questions