[英]Django admin choice field dynamically populated by generic foreign key's model fields
假設我有一些標記應用程序的簡單模型(這從實際代碼中簡化):
# 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正常工作。 這可能嗎? 或者我是否需要一些自定義管理器來在標記模型中實現重復的content_type?
2)我想將管理站點與這些模型一起使用。 是否可以動態創建“content_type_field”字段的選項下拉列表,其中內容對應於使用Tabularinline布局時父模型的所選content_type(即tagTemplate)中的字段列表?
例如。 在管理站點中,我為包含字段('name','age','dob')的新tagTemplate記錄選擇一個模型(content_type字段),我希望TabularInline表單動態更新'content_type_field'到包含選項名稱,年齡和dob。 如果我然后在父tagTemplate content_type字段中選擇不同的模型,則內聯的子tagTemplateItemDisplay content_type_field中的選項將再次更新。
您可以為該模型創建子類的子類
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
覆蓋為管理站點創建的默認表單。
不是一個完整的解決方案,但應該讓你開始。
對於動態表單生成,您可以從閱讀本文開始
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.