Hi,

Looking at Django's forms/fiedls.py may give you some ideas.

The test for an empty value is

if value in validators.EMPTY_VALUES

You can also use self.required to see if the required attribute is set
(e.g., see Field's validate() method).

Of course, a username with a single space will still raise your "User
not found" exception using this method  - but I think it's standard
behaviour for all Fields (try inserting a space in an integer field).

You're also ignoring validators on your custom clean method, but I
guess that's because you know you won't need them :)

"""
The clean() method on a Field subclass. This is responsible for
running to_python, validate and run_validators in the correct order
and propagating their errors. If, at any time, any of the methods
raise ValidationError, the validation stops and that error is raised.
This method returns the clean data, which is then inserted into the
cleaned_data dictionary of the form.
"""
http://docs.djangoproject.com/en/dev/ref/forms/validation/

hth,
Nuno




On Fri, Jul 16, 2010 at 2:01 PM, Paddy Joy <paddy...@gmail.com> wrote:
> I'm trying to create a custom form field that will validate against
> auth.user. The field should throw a validation error if the user does
> not exist, otherwise the field should validate.
>
> So far I have:
>
> class ExistingUserField(forms.CharField):
>    def clean(self, value):
>        # Check if the user exists
>        try:
>            user = User.objects.get(username=value)
>        except:
>            # User does not exist
>            raise forms.ValidationError('User %s not found' % value)
>       return value
>
> I then use this in a form as:
>
> class MyForm(forms.Form):
>    user = ExistingUserField(required=False)
>
> This code works as expected when the user field is populated but does
> not honour the "required=False" argument, when the user field is left
> blank the error "User not found" is raised.
>
> Do i need to check for all forms of None and blank strings? Is there a
> better way?
>
> Paddy
>
> --
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to 
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at 
> http://groups.google.com/group/django-users?hl=en.
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to