Validate form field that include email or emails separated by 'token' kwargs, by default ',' a comma. Return a list [] of email(s). Check validity of the email(s) from django EmailField regex (tested with 1.3, but normally will also work with 1.5)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | # -*- coding: utf-8 -*-
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.core.validators import email_re, EMPTY_VALUES
from django.forms.fields import Field
class CommaSeparatedEmailField(Field):
description = _(u"E-mail address(es)")
def __init__(self, *args, **kwargs):
self.token = kwargs.pop("token", ",")
super(CommaSeparatedEmailField, self).__init__(*args, **kwargs)
def to_python(self, value):
if value in EMPTY_VALUES:
return []
value = [item.strip() for item in value.split(self.token) if item.strip()]
return list(set(value))
def clean(self, value):
"""
Check that the field contains one or more 'comma-separated' emails
and normalizes the data to a list of the email strings.
"""
value = self.to_python(value)
if value in EMPTY_VALUES and self.required:
raise forms.ValidationError(_(u"This field is required."))
for email in value:
if not email_re.match(email):
raise forms.ValidationError(_(u"'%s' is not a valid "
"e-mail address.") % email)
return value
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Using this custom field, raises: AttributeError: 'CommaSeparatedEmailField' object has no attribute 'is_hidden
#
Please login first before commenting.