Search code examples
pythondjangodjango-formsgeopy

Custom field error from try/except in Django view?


I have a form for geocoding an address in my app. If a non-address is entered, the geocoder raises a "GQueryError". Using try/except I'd like to catch this error and send a custom error back to the form that would show up in the "errorlist" like the other errors and be appropriately displayed and styled. Can this be done?


Solution

  • You should write a clean_field_name method and in it capture the error and raise a ValidationError e.g

    class MyForm(forms.Form):
        ...
        # rest of the form
        ...
    
        def clean_address(self):
            address = self.cleaned_data['address']
            try:
                address = geo_clean(address)
            except GQueryError,e:
                raise forms.ValidationError("ooops you are so wrong, %s!"%e)
    
            return address
    

    Read how to clean specific fields