在django admin中动态设置readonly_fields

时间:2014-01-07 02:02:04

标签: python django python-2.7 django-admin

我可以更改readonly_fields课程中的TranslationAdmin,具体取决于正在查看的Translation中某个字段的值吗?如果是这样,我该怎么做?

我唯一想到的是创建一个查看Translation的小部件,并决定是否是一个只读小部件,但这似乎有点过分。

2 个答案:

答案 0 :(得分:11)

您可以在管理员中继承get_readonly_fields()函数,并根据模型的特定字段值设置只读字段

 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)

我希望它会对你有所帮助。

答案 1 :(得分:0)

以下是一个例子:

  • 使用readonly_fields
  • 创建ModelAdmin(GISDataFileAdmin)
  • 继承该ModelAdmin(ShapefileSetAdmin)并向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