In admin I would like to disable a field when modifying object, but make it required when adding new object.
Whats the django way to go about this one?
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.
The simplest way is by using the field option blank=True (docs.djangoproject.com/en/dev/ref/models/fields/#blank).
You would have to add blank=True as well in field definition. If the model field has blank=True, then required is set to False on the form field. Otherwise, required=True.
You can override the admin's get_readonly_fields
method:
class MyModelAdmin(admin.ModelAdmin): def get_readonly_fields(self, request, obj=None): if obj: # editing an existing object return self.readonly_fields + ('field1', 'field2') return self.readonly_fields
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With