我有一個Django應用程序,其中包含一些相當常見的模型:UserProfile
和Organization
。 A UserProfile
或Organization
都可以有0到n個電子郵件,所以我有一個Email
模型,它有一個GenericForeignKey
。 UserProfile
和Organization
型號都有GenericRelation
,稱爲emails
,它指向Email
型號(下面提供的摘要代碼)。用於輸入0到n個電子郵件地址的Django表單
問題:什麼是提供Organization
表單,允許用戶輸入組織的詳細情況,包括0到n的電子郵件地址的最佳方式?
我的Organization
創建視圖是Django class-based view。我傾向於創建一個動態表單並使用Javascript啓用它,以允許用戶根據需要添加儘可能多的電子郵件地址。我將使用django-crispy-forms和django-floppyform來呈現表單,以便在使用Twitter Bootstrap的網站上顯示。
我想過要在表單中嵌入BaseGenericInlineFormset
這樣做,但這對電子郵件地址來說似乎過分了。將表單嵌入到基於類的視圖所提供的表單中也很麻煩。
請注意,Organization
字段phone_numbers
和locations
發生同樣的問題。
代碼
emails.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'
organizations.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'
parent_mixins.py
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.db import models
class Parent_Mixin(models.Model):
parent_type = models.ForeignKey(ContentType,blank=True,null=True)
parent_id = models.PositiveIntegerField(blank=True,null=True)
parent = generic.GenericForeignKey('parent_type', 'parent_id')
class Meta:
abstract = True
app_label = 'core'
我覺得去了解的最佳方式將它們分割這是 - 就像你提到的 - 使用formset(即使它看起來像矯枉過正)。 –
我簡化了這個問題,找到了答案:http://stackoverflow.com/questions/12890919/django-class-based-views-and-formsets/12905947#12905947。 – Erik