0

我有这个模型:

class option(models.Model):
    warval = models.ForeignKey(war)
    caption = models.CharField(max_length=20)
    text = models.TextField(blank=True,null=True)
    url = models.URLField(blank=True,null=True)
    user = models.ForeignKey(User)

而且我有几个模型形式,例如:

class text_option(ModelForm):
    class Meta:
        model = option
        exclude = ('url','warval','user')

class url_option(ModelForm):
    class Meta:
        model = option
        exclude = ('text','warval','user')
    def clean_url(self):
            #processing...

我希望我的用户根据需要创建尽可能多的选项。所以我的选择是使用“formset”。但是如何使用“war”实例实例化表单集中的所有表单(“war”是一个模型)。以及如何在我的表单集中提供上述给定模型表单的所有功能?

4

1 回答 1

0

您可以war通过 url 显式传递实例的 id,例如http://myserver/add_options/1where 1is id of war,然后在视图中使用它来适当地更新选项的外键字段。

另一种选择是将 id 作为表单中的隐式/隐藏输入字段传递,并使用该 id 来标识war视图中的实例。

另一方面,您可以利用继承来简化模型定义。像:

class base_option(models.Model):
    warval = models.ForeignKey(war)
    caption = models.CharField(max_length=20)
    user = models.ForeignKey(User)

class text_option(base_option):
    text = models.TextField(blank=True,null=True)

class url_option(base_option):
    url = models.URLField(blank=True,null=True)
于 2012-07-23T05:24:38.050 回答