2010-02-01 79 views
2

我添加了一個自定義字段到的ModelForm在管理使用:如何從管理員動態排除非模型字段?

class MyModel(models.Model): 
    name = models.CharField(max_length=64) 
    ...etc... 

class MyModelAdminForm(forms.ModelForm): 
    dynamicfield = forms.IntegerField() 

    def __init__(self, *args, **kwargs): 
     super(MyModelAdminForm, self).__init__(*args, **kwargs) 
     if 'instance' in kwargs: 
      #remove dynamicfield from the form, somehow? 

    def save(self, *args, **kwargs): 
     #do something with dynamicfield 
     super(MyModelAdminForm, self).save(*args, **kwargs) 

    class Meta: 
     model = MyModel 

class MyModelAdmin(admin.ModelAdmin): 
    form = MyModelAdminForm 

admin.site.register(MyModel, MyModelAdmin) 

這一領域的重點是收集初始對象創建過程中需要更多的數據。因此,它應該只在創建新對象時出現(檢查「實例」)。

我遇到的問題是在編輯現有對象時使字段消失。我試過了:

self.fields['dynamicfield'].widget = self.fields['dynamicfield'].hidden_widget() 

但是,只有擺脫了文本輸入字段,而不是標籤。

我還試圖對這些變化(也使用base_fields到位領域的super()調用之前):

del self.fields['dynamicfield'] #yields error: 

TemplateSyntaxError at /admin/db/myapp/mymodel/6/ 
Caught an exception while rendering: Key 'dynamicfield' not found in Form 


self.fields['dynamicfield'].hidden = True #Does nothing. 

self.fields['dynamicfield'] = None #yields error: 

TemplateSyntaxError at /admin/db/catalog/product/6/ 
Caught an exception while rendering: 'NoneType' object has no attribute 'label'  

之前做這些)調用超(也嘗試過,但也失敗:

del self.base_fields['dynamicfield'] #yields error: 
TemplateSyntaxError at /admin/db/myapp/mymodel/6/ 
Caught an exception while rendering: Key 'dynamicfield' not found in Form 

回答

0

試試這個:

def __init__(self, *args, **kwargs): 

     if 'instance' in kwargs: 
      del self.base_fields['dynamicfield'] 
     super(MyModelAdminForm, self).__init__(*args, **kwargs) 
+1

已經嘗試過那個。與del self.fields ['dynamicfield'](上面)完全相同的錯誤。 – Sam 2010-02-01 21:32:13

0

如果刪除不起作用(我不知道爲什麼),那麼動態添加呢?

def __init__(self, *args, **kwargs): 
    super(MyModelAdminForm, self).__init__(*args, **kwargs) 
    if 'instance' not in kwargs: 
     self.fields['dynamicfield'] = forms.IntegerField() 

這裏還有一個關於如何create dynamic forms的鏈接。 (我認爲這甚至是啓動Django的人?)

相關問題