2009-09-18 34 views
3

說我有一些標記應用下面的簡單模型(這是從實際代碼的簡化):Django管理選擇現場由通用外鍵的模型字段動態填充

# 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'字段的選擇下拉列表,其中的內容對應於父模型的選定content_type(即tagTemplate)中的字段列表?

例如。在管理站點中,我爲包含字段('name','age','dob')的新tagTemplate記錄選擇模型(content_type字段),我希望TabularInline表單動態更新'content_type_field'到包含選項名稱,年齡和dob。如果我然後在父tagTemplate content_type字段中選擇不同的模型,則會再次更新內聯的子tagTemplateItemDisplay content_type_field中的選項。

回答

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