2011-03-21 159 views
0

是否有像get_list_display()這樣的管理模型方法或某種方式可以設置不同的list_display值?Django管理員:有條件地設置list_display

class FooAdmin (model.ModelAdmin): 
    # ... 
    def get_list_display(): 
     if some_cond: 
      return ('field', 'tuple',) 
     return ('other', 'field', 'tuple',) 

回答

0

您是否嘗試過使用該屬性?

class FooAdmin(admin.ModelAdmin): 
    @property 
    def list_display(self): 
     if some_cond: 
      return ('field','tuple') 
     return ('other','field','tuple') 

我沒有,但它可能工作。

我也相當肯定,你可以拼一下:

​​

但是這一次將只能運行在FooAdmin類被解釋的時候檢查:但如果你是立足於settings.SOME_VALUE測試例如,那麼它可能工作。

另請注意,第一個示例中的self是FooAdmin類的實例,而不是Foo本身。

0

你想覆蓋admin.ModelAdmin類的changelist_view方法:

def changelist_view(self, request, extra_context=None): 
    # just in case you are having problems with carry over from previous 
    # iterations of the view, always SET the self.list_display instead of adding 
    # to it 

    if something: 
    self.list_display = ['action_checkbox'] + ['dynamic_field_1'] 
    else: 
    self.list_display = ['action_checkbox'] + ['dynamic_field_2'] 

    return super(MyModelAdminClass, self).changelist_view(request, extra_context) 

的「action_checkbox」是什麼Django使用要知道在左側的動作下降顯示覆選框下來,所以請確保在設置self.list_display時包含它。像往常一樣,如果您只是簡單地爲ModelAdmin類設置list_display,通常不需要包含它。

相關問題