Django admin 选择字段动态填充通用外键模型字段
假设我有一些简单的模型,用于一个标签应用程序(这比实际代码简单很多):
# 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) 在标记为 * 的那一行,我从文档中了解到,我需要根据内容类型框架传递两个字段名。在我的情况下,content_type 字段是在模板模型中指定的。我想避免在 'tag' 模型中重复出现 content_type 字段,以使 GenericForeignKey 正常工作。这可能吗?还是我需要一些自定义管理器来在 tag 模型中实现重复的 content_type?
2) 我想在这些模型中使用管理网站。是否可以动态创建一个下拉选择框,用于 'content_type_field' 字段,其中的内容对应于从所选的父模型(即 tagTemplate)中的 content_type 列表中获取的字段?当使用 Tabularinline 布局时,这样做可以吗?
例如,在管理网站中,我选择一个模型(content_type 字段)来为新的 tagTemplate 记录,这个记录包含字段('name', 'age', 'dob'),我希望 TabularInline 表单能够动态更新 'content_type_field',使其包含选择项 name、age 和 dob。如果我在父级 tagTemplate 的 content_type 字段中选择了不同的模型,那么子级 tagTemplateItemDisplay 的 content_type_field 选择项也会再次更新。
1 个回答
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
这样可以覆盖为管理网站自动生成的默认表单。
这不是一个完整的解决方案,但可以帮助你入门。
关于动态表单生成,你可以先 看看这个链接。