【发布时间】:2014-01-24 14:35:47
【问题描述】:
我能否根据正在查看的Translation 中某个字段的值更改我的TranslationAdmin 类中的readonly_fields?如果是这样,我该怎么做?
我想出的唯一方法是制作一个查看Translation 并决定是否为只读小部件的小部件,但这似乎有点矫枉过正。
【问题讨论】:
标签: python django python-2.7 django-admin
我能否根据正在查看的Translation 中某个字段的值更改我的TranslationAdmin 类中的readonly_fields?如果是这样,我该怎么做?
我想出的唯一方法是制作一个查看Translation 并决定是否为只读小部件的小部件,但这似乎有点矫枉过正。
【问题讨论】:
标签: python django python-2.7 django-admin
你可以在你的后台继承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)
希望对你有帮助。
【讨论】:
这是一个例子:
从该 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
【讨论】: