【问题标题】:Django admin choice field dynamically populated by generic foreign key's model fields由通用外键的模型字段动态填充的 Django 管理选择字段
【发布时间】:2010-11-29 11:56:42
【问题描述】:

假设我有一些标记应用程序的以下简单模型(这是从实际代码中简化的):

# 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 字段是在模板模型中指定的。我想避免在“标签”模型中使用重复的 content_type 字段以使 GenericForeignKey 正常工作。这可能吗?还是我需要一些自定义管理器来在标签模型中实现重复的 content_type?

2) 我想将管理站点与这些模型一起使用。使用 Tabularinline 布局时,是否可以为“content_type_field”字段动态创建选择下拉列表,其中内容对应于父模型(即 tagTemplate)的所选 content_type 字段列表?

例如。在管理站点中,我为包含字段('name'、'age'、'dob')的新 tagTemplate 记录选择模型(content_type 字段),我希望 TabularInline 表单动态更新 'content_type_field'包含选项名称、年龄和出生日期。如果我随后在父 tagTemplate content_type 字段中选择不同的模型,则内联的子 tagTemplateItemDisplay content_type_field 中的选项将再次更新。

【问题讨论】:

    标签: python django django-models django-admin


    【解决方案1】:

    您可以为该模型子类化表单

    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 模型中你需要:

    form = TagTemplateForm
    

    覆盖为管理站点创建的默认表单。

    不是一个完整的解决方案,但应该可以帮助您入门。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-25
      • 2013-07-22
      • 2021-03-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多