Django readonly field only on change, but not when creating

django, django-admin, django-models

Solution

You need to override `get_readonly_fields()` method of your admin class.

# 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 []

Problem

I have a `Team` model whit `players` ManyToManyField, and I want to be able to add `Player`s to a new team when created, but not able to modify it after created. If I make the `players` field readonly like this: ``` # admin.py class TeamAdmin(admin.ModelAdmin) readonly_fields = ['players'] admin.site.register(Team, TeamAdmin) ``` I will not be able to add players to a new `Team`. How can I make the `players` field "readonly after created" or something like that?

Original source