Django readonly字段仅在更改时,但在创建时不会

时间:2013-07-12 11:07:57

标签: django django-models django-admin

我有Team模型whit players ManyToManyField,我希望能够在创建时将Player添加到新团队,但在创建后无法修改它。

如果我将players字段设为只读:

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

admin.site.register(Team, TeamAdmin)

我无法将玩家添加到新Team。 如何使players字段“在创建之后只读”或类似的东西?

1 个答案:

答案 0 :(得分:41)

您需要覆盖管理类的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 []