0

model.py

from django.core.exceptions import ValidationError

def surname_validate(value):
if value == "123":
    raise ValidationError('is not an even number')


class Member(models.Model):
surname=models.CharField(max_length=50,validators=[surname_validate])
other_names=models.CharField(max_length=150,null=True, blank=True)

forms.py

class MemberEditForm(forms.ModelForm):
class Meta:
    model=Member

When i try to save the form with no inputs, i get the default 'this field is required' error so I know my views are correct. The thing is that my validation for surname field does not work at all and i dont understand. What am I doing wrong here. Why wont it work ??? This is frustrating

Nathaniel
  • 666
  • 4
  • 15
flexxxit
  • 2,440
  • 5
  • 42
  • 69

2 Answers2

0

Actually Model Validation not work for ModelForm. If you want to have a validation for surname in your form, you must write validation for the form in its clean method.

So, your form must be like this:

class MemberEditForm(forms.ModelForm):

    class Meta:
        model = Member

    surname = forms.CharField(max_length = 50, required = True, error_messages = {'my_error': 'is not an even number'})

    def clean_surname(self):
        if self.cleaned_data['surname'] == '123':
            raise ValidationError(self.fields['surname'].error_messages['my_error'])
        return self.cleaned_data['surname']
  • clean_surname function is never called. its still not working – flexxxit Jan 24 '13 at 11:49
  • Actually your answer is true. But you turn your way. There is a simple way to do it. Show your view if you can. –  Jan 26 '13 at 16:21
0

I finally used this and it worked

attrs_dict = {'class': 'required'}

class MemberEditForm(forms.ModelForm):

class Meta:
    model = Member

surname = forms.RegexField(#regex=r'^[\w.@+-]+$',
    regex=r'^$',# my validation here
    max_length=50,
    widget=forms.TextInput(attrs=attrs_dict),
    label=_("Surname*"),
    error_messages={'invalid': _("Invalid Entry.")})

Thanks

flexxxit
  • 2,440
  • 5
  • 42
  • 69