zer0c00l
zer0c00l

Reputation: 303

django form validation: validating initial values

I have a django form (forms.Form). Each and every form fields have initial values like,


class SomeForm(forms.Form):
  city = forms.CharField(initial="Your city here")


When some one posts this form without changing the initial value (ie. Without entering anything as city, the city field will be "Your city here") . form.is_valid() does not raise a validation error. Is there any way i can make the validation fail? Is there any inbuilt method/property available that i can call/set to make form validation to fail? Or do i have to manually validate it?

Upvotes: 1

Views: 1304

Answers (1)

sidhshar
sidhshar

Reputation: 1061

You would have to manually do the validation using the Django forms clean_fieldname method as follows:

class SomeForm(forms.Form):
    city = forms.CharField(initial='Your city here')

    def clean_city(self):
        city_name = self.cleaned_data['city']
        if city_name in ['Your city here']:
            raise forms.ValidationError('Enter a city name.')
        return city_name

If you are using Django 1.2 or upwards, custom validators would be worth the effort.

Upvotes: 7

Related Questions