different fields for add and change pages in admin

前端 未结 9 768
日久生厌
日久生厌 2020-12-05 00:37

I have a django app with the following class in my admin.py:

class SoftwareVersionAdmin(ModelAdmin):
    fields = (\"product\", \"version_number\", \"descrip         


        
9条回答
  •  猫巷女王i
    2020-12-05 00:53

    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)
    

提交回复
热议问题