自定义Django字段来存储电子邮件地址列表 [英] Custom Django Field to store a list of email addresses
问题描述
我正在尝试将一个字段添加到Django模型中,该模型将代表一个电子邮件地址列表。我希望用户在管理员的表单中输入逗号分隔的地址列表,然后我的应用程序将解析发送一系列电子邮件。
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.
我的目前的实施涵盖了基本思想,但具有重大的局限性。在管理员中,如果我输入像 foo@example.com,bar@example.com
之类的字符串,则将其正确地写入数据库 [u'foo@example.com',u'bar@example.com']
。但管理员显示这个序列化的值而不是人性化的字符串。更重要的是,如果我编辑并保存记录,而不进行任何更改,相同的转换将更改 [u'foo@example.com',u'bar@example.com']
to [u[u'foo@example.com',uu'bar@example.com']]
。
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']"]
.
如何将python列表表单转换回管理员中使用的字符串?这是否是 value_to_string
方法的目的,还是需要将其转换为别的地方?
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)
这是基于这里描述的 SeparatedValuesField
: http://www.davidcramer.net/code/181/custom-fields-in-django.html 。
This is based on the SeparatedValuesField
described here: http://www.davidcramer.net/code/181/custom-fields-in-django.html.
推荐答案
我不会这样做。我会做任何你的 EmailListField
应该是与电子邮件地址字段一对多关联。
I wouldn't do that. I would make whatever your EmailListField
is supposed to be associated with be one-to-many with email address fields.
这篇关于自定义Django字段来存储电子邮件地址列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!