我有一个Phone模型,许多不同模型经常使用它作为通用关系。我不知道如何将它包含在这些模型的创建/更新表单中......一个想法的优点或缺点是在forms.ModelForm子类中包含额外的字段......有点像这样:
###### models.py
class UpstreamContactModel(models.Model):
client = models.ForeignKey(UpstreamClientModel,
related_name='contacts')
contact_type = models.CharField(max_length=50, default='Main',
blank=True, null=True)
name = models.CharField(max_length=100, unique=True)
job_title = models.CharField(max_length=50, blank=True, null=True)
email = models.EmailField(blank=True, null=True)
skype_id = models.CharField(max_length=30, blank=True, null=True)
phones = generic.GenericRelation(Phone)
notes = models.TextField(blank=True, null=True)
def __unicode__(self):
return self.name
class Meta:
verbose_name = 'Contact'
class Phone(models.Model):
info = models.CharField('Eg. Office, Personal, etc',
max_length=15, blank=True)
number = models.CharField('Phone numbes', max_length=20)
# generic relationships so I can attach to other objects later on
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
def __unicode__(self):
return self.number
##### forms.py
class ContactForm(forms.ModelForm, BaseValidationForm):
info = forms.CharField(max_length=15)
number = forms.CharField(max_length=20)
class Meta:
model = UpstreamContactModel
def clean(self):
???
def save(self):
???
我一直试图找出人们在涉及一般关系时如何处理CRUD,但到目前为止我还没有成功。
答案 0 :(得分:1)
如果您使用模型表单,则可以看到它们使用的表单元素类型。
对于content_type,它通常使用带有ContentType.objects.all()的ModelChoiceField作为查询集,而object_id将是一个查找正整数的TextInput。如果您使用模型表单,我认为实际的通用访问器不会显示在表单中。
如果你想要一个比这更优雅的解决方案,我会考虑编写一个自定义表单字段或小部件来处理它。
我不认为将其他字段添加到ModelForm是不好的做法,事实上我认为这是一个很好的途径。覆盖save方法可能会为您提供所需的功能。