Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django readonly field only on change, but not when creating

I have a Team model whit players ManyToManyField, and I want to be able to add Players 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?

like image 913
kissgyorgy Avatar asked Jul 12 '13 11:07

kissgyorgy


People also ask

How do you make a field non editable in Django?

django-forms Using Model Form Making fields not editable Django 1.9 added the Field. disabled attribute: The disabled boolean argument, when set to True, disables a form field using the disabled HTML attribute so that it won't be editable by users.

How do you make a field non mandatory in Django admin?

The simplest way is by using the field option blank=True (docs.djangoproject.com/en/dev/ref/models/fields/#blank).

When saving How can you check if a field has changed Django?

Since Django 1.8 released, you can use from_db classmethod to cache old value of remote_image. Then in save method you can compare old and new value of field to check if the value has changed. @classmethod def from_db(cls, db, field_names, values): new = super(Alias, cls).

How do I make a field read only in Django admin?

Django admin by default shows all fields as editable and this fields option will display its data as-is and non-editable. we use readonly_fields is used without defining explicit ordering through ModelAdmin or ModelAdmin. fieldsets they will be added. Now we make the Question text fields read-only.


1 Answers

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 [] 
like image 120
Sudipta Avatar answered Sep 21 '22 22:09

Sudipta