Dynamically setting readonly_fields in django admi

2019-06-28 03:37发布

问题:

Can I change readonly_fields in my TranslationAdmin class dependent on the value of a certain field in the Translation being viewed? If so, how would I do that?

The only thing I've come up with is to make a widget that looks at the Translation and decides whether to be a readonly widget or not, but that seems like overkill for this.

回答1:

You can inherit the function get_readonly_fields() in your admin and set readonly fields according your model's certain field value

 class TranslationAdmin(admin.ModelAdmin):
        ...

        def get_readonly_fields(self, request, obj=None):
            if obj.certainfield == something:
                return ('field1', 'field2')
            else:
                return super(TranslationAdmin, self).get_readonly_fields(request, obj)

I hope it will help you.



回答2:

Here is an example of:

  • Creating a ModelAdmin (GISDataFileAdmin) with readonly_fields
  • Inheriting from that ModelAdmin (ShapefileSetAdmin) and adding an additional value to readonly_fields

    class GISDataFileAdmin(admin.ModelAdmin):
    
        # Note(!): this is a list, NOT a tuple
        readonly_fields = ['modified', 'created', 'md5',]
    
    class ShapefileSetAdmin(GISDataFileAdmin):    
    
        def get_readonly_fields(self, request, obj=None):
            # inherits readonly_fields from GISDataFileAdmin and adds another
    
            # retrieve current readonly fields 
            ro_fields = super(ShapefileSetAdmin, self).get_readonly_fields(request, obj)
    
            # check if new field already exists, if not, add it
            #
            # Note: removing the 'if not' check will add the new read-only field
            #   each time you go to the 'add' page in the admin
            #   e.g., you can end up with:
            # ['modified', 'created', 'md5', 'shapefile_load_path', 'shapefile_load_path, 'shapefile_load_path', etc.]
            #
            if not 'shapefile_load_path' in ro_fields:
                ro_fields.append('shapefile_load_path')
    
            return ro_fields