【问题标题】:Django Forms for generic relationships. How to include them?用于通用关系的 Django 表单。如何包括它们?
【发布时间】:2012-12-23 11:58:43
【问题描述】:

我有一个电话模型,它被许多不同的模型用作通用关系。我不知道如何将它包含在这些模型的创建/更新表单中……在 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,但到目前为止我没有成功。

【问题讨论】:

  • 许多年后,仍在寻找使用 CBV 回答此问题的完整代码示例...如果您能够实现这一点,如果您能分享解决方案,那就太好了。跨度>
  • 我说即使使用任何类型的视图。仍然搜索例如如何做到这一点。

标签: django forms django-forms django-generic-views


【解决方案1】:

如果你使用模型表单,你可以看到他们使用了什么样的表单元素。

对于 content_type,它通常使用带有 ContentType.objects.all() 的 ModelChoiceField 作为查询集,而 object_id 将是一个寻找正整数的 TextInput。如果您使用模型表单,我认为实际的通用访问器不会出现在表单中。

如果您想要一个比这更优雅的解决方案,我会考虑编写一个自定义表单字段或小部件来处理它。

我认为向 ModelForm 添加其他字段并不是一个坏习惯,事实上,我认为这是一个很好的方法。覆盖 save 方法可能会为您提供所需的功能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-04
    • 2012-01-23
    • 1970-01-01
    • 2013-07-28
    • 1970-01-01
    • 2013-09-09
    • 2016-06-11
    • 1970-01-01
    相关资源
    最近更新 更多