Created
November 14, 2012 04:01
-
-
Save gterzian/4070180 to your computer and use it in GitHub Desktop.
Django custom form field checks that any input email is from a registered user, multiple comma delimitated input accepted
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django import forms | |
from django.core.exceptions import ValidationError | |
from django.contrib.auth.models import User | |
class UserEmailField(forms.EmailField): | |
''' | |
This field subclasses EmailField, so we get the validation that no blanks are supplied and that an actual email address was supplied | |
This custom field adds validation for the existence of a registered user with this email. | |
''' | |
def to_python(self, value): | |
#call the super to_python, which returns a unicode object, trim any whitespace left between emails by the user, then create a list of emails | |
value = super(UserEmailField, self).to_python(value).strip().replace(' ', '').split(',') | |
#remove any 'empty' email, which would be caused by the user leaving a trailing comma | |
value = [email for email in value if email != u''] | |
return value | |
def find_user(self, value): | |
errorlist = [] | |
for email in value: | |
#value is list returned by to_python | |
#if we don't find a user for an email, add it to the list of errors | |
try: | |
User.objects.get(email=email) | |
except: | |
errorlist.append(email) | |
if errorlist: | |
#raise a field error | |
raise forms.ValidationError(u"we haven't found a user for the following email(s): '%s'" % ( ', '.join(errorlist))) | |
def clean(self, value): | |
#run all the default validation, then call find_user | |
value = self.to_python(value) | |
for email in value: | |
#check that each email in the list is a real email | |
self.run_validators(email) | |
#validate checks that something was imput, or raises 'field is required' | |
self.validate(value) | |
#find_user checks that each email supplied belongs to a registered user | |
self.find_user(value) | |
return value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment