Frage

Django: If I don't want to call clean_() method, can I do it?

class myForm(forms.Form):
    userId = forms.CharField(max_length=30, required=False,)
    email = forms.EmailField(required=False,)

    def clean_userId(self):
        if 'userId' in self.cleaned_data:
            if not re.search(r'^\w+$', self.cleaned_data['userId']):
                raise forms.ValidationError('Invalid ID')
            try:
                User.objects.get(username=self.cleaned_data['userId'])
            except ObjectDoesNotExist:
                return self.cleaned_data['userId']
            raise raise forms.ValidationError('Invalid ID')
        else:
            raise raise forms.ValidationError('Invalid ID')

Sometimes, I want to use Form validation in order to validate only 'email' field.

Like below:

>>> form = myForm({'email':'abc@com'})
>>> form.cleaned_data['email']
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'myForm' object has no attribute 'cleaned_data'
>>> print form.errors
<ul class="errorlist"><li>workers<ul class="errorlist"><li>Invalid ID</li></ul>

Is there the way?

War es hilfreich?

Lösung

You could try something like:

form = myForm({'email':'abc@com'})
try:
    form.clean_email()
except forms.ValidationError:
    #do whatever
else:
    #do whatever

is_valid() will call clean on everything, so just call whatever clean method you want.

You could also just have two different forms or a form that inherits from another, this would be a lot better IMO.

Andere Tipps

You don't need define clean_userId() or clean_email(), just define clean(), do all in that method of Form.

class MyForm(forms.Form):
    # fields

    def clean(self):
        cleaned_data = super(MyForm, self).clean()
        email = cleaned_data.get('email')

        # do some validation

        return cleaned_data

Before you access cleaned_data, remember call form.is_valid().

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top