我有一个 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,但到目前为止我一直没有成功。
最佳答案
如果您使用模型表单,您可以看到他们使用什么样的表单元素。
对于 content_type,它通常使用带有 ContentType.objects.all() 的 ModelChoiceField 作为查询集,而 object_id 将是一个寻找正整数的 TextInput。如果您使用模型表单,我认为实际的通用访问器不会出现在表单中。
如果您想要一个比这更优雅的解决方案,我会考虑编写一个自定义表单字段或小部件来处理它。
我认为向 ModelForm 添加其他字段并不是坏习惯,事实上我认为这是一个很好的途径。覆盖 save 方法可能会给你你想要的功能。
关于用于通用关系的 Django 表单。如何包含它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14235199/