Django admin choice字段由通用外键的模型字段动态填充

2024-10-01 09:41:22 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是一些简单的应用程序(例如,我有一些简化的代码):

# Model of tag templates
class TagTemplate(models.Model):
    name = models.CharField()
    content_type = models.ForeignKey(ContentType)

class Tag(models.Model):
    template = models.ForeignKey(TagTemplate)
    object_id = models.PositiveIntegerField()
 *  content_object = generic.GenericForeignKey('template__content_type', 'object_id') 

# Each tag may display the 
class TagTemplateItemDisplay(models.Model):
    template = models.ForeignKey(TagTemplate)
    content_type_field = models.CharField()
    font_size = models.IntegerField()

我有两个问题:

1)在标有*的行中,我从文档中了解到,我需要根据contenttype框架传递两个字段名。在我的例子中,content_type字段是在模板模型中指定的。我希望避免在“tag”模型中使用重复的content_type字段,以使GenericForeignKey正常工作。这可能吗?或者我需要一些自定义管理器来在标记模型中实现重复的内容类型吗?在

2)我想使用这些模型的管理网站。当使用表格线布局时,是否可以为“content_type_field”字段动态创建一个选项下拉列表,其中的内容对应于父模型(即tagTemplate)所选内容类型的字段列表?在

例如,在管理站点中,我为包含字段('name'、'age'、'dob')的新tagTemplate记录选择一个模型(content_type field),我希望tabarinline表单动态更新“content_type_field”,以包含name、age和dob选项。如果我随后在父tagTemplate content_type字段中选择其他模型,则内联的子tagTemplateItemDisplay content_type_字段中的选项将再次更新。在


Tags: name模型field内容modelobjectmodelstag
1条回答
网友
1楼 · 发布于 2024-10-01 09:41:22

您可以将该模型的窗体子类化

class TagTemplateForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(TagTemplateForm, self).__init__(*args, **kwargs)
        if self.instance.content_type == SomeContentType:
            **dynamically create your fields here**
        elif self.instance.content_type == SomeOtherContentType:
            **dynamically create your other fields here**

那么在您的TagAdmin模型中,您需要:

^{pr2}$

重写为管理站点创建的默认表单。在

但你不应该得到一个完整的解决方案。在

对于动态表单生成,可以从reading over this开始

相关问题 更多 >