简体   繁体   English

在django admin中动态设置readonly_fields

[英]Dynamically setting readonly_fields in django admin

Can I change readonly_fields in my TranslationAdmin class dependent on the value of a certain field in the Translation being viewed? 我可以更改TranslationAdmin类中的readonly_fields ,具体取决于正在查看的Translation某个字段的值吗? 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. 我唯一想到的是创建一个查看Translation的小部件,并决定是否是一个只读小部件,但这似乎有点矫枉过正。

You can inherit the function get_readonly_fields() in your admin and set readonly fields according your model's certain field value 您可以在管理员中继承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)

I hope it will help you. 我希望它会对你有所帮助。

Here is an example of: 这是一个例子:

  • Creating a ModelAdmin (GISDataFileAdmin) with readonly_fields 使用readonly_fields创建ModelAdmin(GISDataFileAdmin)
  • Inheriting from that ModelAdmin (ShapefileSetAdmin) and adding an additional value to readonly_fields 继承自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 # eg, 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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM