I have a django app with the following class in my admin.py:
class SoftwareVersionAdmin(ModelAdmin):
fields = (\"product\", \"version_number\", \"descrip
dpawlows' solution above is the clearest, I think.
However, I encountered an additional issue in that type of structure.
If change_view() makes changes to the model, e.g. specifies readonly_fields that have been filled in in add_view(), these changes persist in add_view() after change_view() has been called. For example:
def add_view(self, request, extra_context=None):
return super().add_view(request)
def change_view(self, request, object_id, extra_context=None):
self.readonly_fields = ['name'] # this change persists in add_view()
return super().change_view(self, request, object_id)
In this case, after change_view() has been called on any instance, invoking add_view() will show readonly_fields ("name", in this case) set by change_view() and thus protect these fields from filling in.
This can be solved by adding a 'roll back' assignment in add_view():
def add_view(self, request, extra_context=None):
self.readonly_fields = [] # 'roll back' for changes made by change_view()
return super().add_view(request)