How to make a field in Django Admin readonly or non-editable based on the value from another field?
I have used readonly_fields=('amount',)
but this wont fix my problem , as I need to manage it based on another field .
Asked
Active
Viewed 2.0k times
13

coffee-grinder
- 26,940
- 19
- 56
- 82

Ani Varghese
- 403
- 2
- 6
- 17
3 Answers
29
You can override the admin's get_readonly_fields
method:
class MyAdmin(admin.ModelAdmin):
def get_readonly_fields(self, request, obj=None):
if obj and obj.another_field == 'cant_change_amount':
return self.readonly_fields + ('amount',)
return self.readonly_fields

mVChr
- 49,587
- 11
- 107
- 104
-
1Can this be done while maintaing the field ordering? – markwalker_ May 23 '14 at 10:09
1
For filling out one field from another, you need to add a prepopulated_fields
attribute to the relevant ModelAdmin
class. For example:
class PostAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("title",)}
The relevant documentation can be found here.
However, in the version of django I'm using at the moment (1.3), this seems to create an error when readonly_fields
is also used.

samfrances
- 3,405
- 3
- 25
- 40
0
Declare any permanently readonly_fields in the body of the class, as the readonly_fields class attribute will be accessed from validation

Abin Abraham
- 497
- 2
- 11
- 26