Model Field allowing to store multiple emails in one textual field. Emails separated by comma. All emails are validated. Works with Django admin.
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 37 | from django.core import validators
from django.db import models
class EmailListField(models.CharField):
__metaclass__ = models.SubfieldBase
class EmailListValidator(validators.EmailValidator):
def __call__(self, value):
for email in value:
super(EmailListField.EmailListValidator, self).__call__(email)
class Presentation(list):
def __unicode__(self):
return u", ".join(self)
def __str__(self):
return ", ".join(self)
default_validators = [EmailListValidator()]
def get_db_prep_value(self, value, *args, **kwargs):
if not value:
return
return ','.join(unicode(s) for s in value)
def value_to_string(self, obj):
value = self._get_val_from_obj(obj)
return self.get_db_prep_value(value)
def to_python(self, value):
if not value:
return
if isinstance(value, self.Presentation):
return value
return self.Presentation([address.strip() for address in value.split(',')])
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 8 months ago
Comments
… And a small diff for python 3 (nota: this code is not python2 compatible):
#
btw, works like a charm with django 1.7
#
Please login first before commenting.