2013-07-12 72 views
15

我有Team型號惠特players ManyToManyField,我希望能夠在創建時將Player添加到新團隊,但無法在創建後對其進行修改。Django只讀字段只在更改時創建,但不創建時

如果我做players場只讀這樣的:

# admin.py 
class TeamAdmin(admin.ModelAdmin) 
    readonly_fields = ['players'] 

admin.site.register(Team, TeamAdmin) 

我不能給玩家添加到新Team。 我怎樣才能使players字段「創建後只讀」或類似的東西?

回答

32

您需要覆蓋您的管理員類的get_readonly_fields()方法。

# admin.py 
class TeamAdmin(admin.ModelAdmin) 
    ... 

    def get_readonly_fields(self, request, obj=None): 
     if obj: #This is the case when obj is already created i.e. it's an edit 
      return ['players'] 
     else: 
      return [] 
+0

完美,謝謝! – kissgyorgy