Login

Multiple emails field

Author:
cuchac
Posted:
May 6, 2014
Language:
Python
Version:
1.5
Tags:
multiple email validation mail multifield
Score:
0 (after 0 ratings)

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

  1. Multiple emails form field by matrix 1 year, 8 months ago
  2. Multiple emails form field by virhilo 5 years, 5 months ago
  3. MultipleEmailsField by spanasik 6 years, 4 months ago
  4. Email validation by mulamvenky 2 years, 3 months ago
  5. EmailListField for Django by sciyoshi 6 years ago

Comments

JocelynD (on July 28, 2014):

… And a small diff for python 3 (nota: this code is not python2 compatible):

-class EmailListField(models.CharField):
+class EmailListField(models.CharField, metaclass=models.SubfieldBase):

-    __metaclass__ = models.SubfieldBase

-        def __unicode__(self):
-            return ", ".join(self)

-            return ", ".join(self)
+            return ",".join(self)

#

JocelynD (on July 28, 2014):

btw, works like a charm with django 1.7

#

Please login first before commenting.