I'm trying to add a field to a Django model that will represent a list of email addresses. I would like a user to enter a comma separated list of addresses into a form in the admin, which my app will then parse to send out a series of emails.
My current implementation covers the basic idea, but has a significant limitation. In the admin, if I enter a string like foo@example.com, bar@example.com
, then it correctly writes this to the database as [u'foo@example.com', u'bar@example.com']
. But the admin displays this serialized value instead of the humanized string. More importantly, if I edit and save the record, without making any changes, the same conversion changes [u'foo@example.com', u'bar@example.com']
to [u"[u'foo@example.com'", u"u'bar@example.com']"]
.
How do I convert the python list representation back to a string for use in the admin? Is that the purpose of the value_to_string
method or do I need to make the conversion someplace else?
My current custom model field is as follows:
class EmailListField(models.TextField):
__metaclass__ = models.SubfieldBase
def to_python(self, value):
if not value:
return
if isinstance(value, list):
return value
return [address.strip() for address in value.split(',')]
def get_db_prep_value(self, value):
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)
This is based on the SeparatedValuesField
described here: http://www.davidcramer.net/code/181/custom-fields-in-django.html.