我有一个Django应用程序,其中包含一些相当常见的模型:UserProfile
和Organization
。 UserProfile
或Organization
都可以包含0到n封电子邮件,因此我的Email
模型有GenericForeignKey
。 UserProfile
和Organization
模型都有一个名为GenericRelation
的{{1}},指向emails
模型(下面提供的摘要代码)。
问题:提供Email
表单的最佳方式是什么,允许用户输入组织详细信息,包括0到n个电子邮件地址?
我的Organization
创建视图是Django class-based view。我倾向于创建一个动态表单并使用Javascript启用它,以允许用户根据需要添加尽可能多的电子邮件地址。我将使用django-crispy-forms和django-floppyforms呈现表单,以便在使用Twitter Bootstrap的网站上显示。
我已经考虑过在表单中嵌入Organization
这样做,但这似乎对电子邮件地址有些过分。将表单集嵌入由基于类的视图提供的表单中也很麻烦。
请注意,BaseGenericInlineFormset
字段Organization
和phone_numbers
会出现同样的问题。
代码
emails.py:
locations
organizations.py:
from django.db import models
from parent_mixins import Parent_Mixin
class Email(Parent_Mixin,models.Model):
email_type = models.CharField(blank=True,max_length=100,null=True,default=None,verbose_name='Email Type')
email = models.EmailField()
class Meta:
app_label = 'core'
parent_mixins.py
from emails import Email
from locations import Location
from phone_numbers import Phone_Number
from django.contrib.contenttypes import generic
from django.db import models
class Organization(models.Model):
active = models.BooleanField()
duns_number = models.CharField(blank=True,default=None,null=True,max_length=9) # need to validate this
emails = generic.GenericRelation(Email,content_type_field='parent_type',object_id_field='parent_id')
legal_name = models.CharField(blank=True,default=None,null=True,max_length=200)
locations = generic.GenericRelation(Location,content_type_field='parent_type',object_id_field='parent_id')
name = models.CharField(blank=True,default=None,null=True,max_length=200)
organization_group = models.CharField(blank=True,default=None,null=True,max_length=200)
organization_type = models.CharField(blank=True,default=None,null=True,max_length=200)
phone_numbers = generic.GenericRelation(Phone_Number,content_type_field='parent_type',object_id_field='parent_id')
taxpayer_id_number = models.CharField(blank=True,default=None,null=True,max_length=9) # need to validate this
class Meta:
app_label = 'core'
答案 0 :(得分:2)
您可以尝试使用.split(),这样您的表单看起来会更容易,用户也不必继续添加文本字段。 你可以做的是,制作一个文本框,用户可以在其中添加多个电子邮件并将其分开。然后在你的观点中你可以做到这一点
email = emails.split(',')
for i in emails:
#assign email and save.
如果有电子邮件类型
建立这样的系统可能仍然是一个好主意。你能做的是
ABC @ gmail.com工作,XYZ @ k.com校
然后你可以像这样拆分它们
email-type=email.split(',')
for i in email-type:
email=i.split('-')[0]
if i.split('-')[1]:
type=i.split('-')[1]
else:
#give it a default type