变量作为字段选项中的参数

时间:2008-10-15 20:16:33

标签: python django

我想创建一个模型,在创建时设置editable = False,在编辑项目时设置editable = True。我认为它应该是这样的:

 home = models.ForeignKey(Team, editable=lambda self: True if self.id else False)

但它不起作用。也许覆盖 init 的东西可以帮助我,但我不知道什么可以做到这一点。我知道我可以在save()方法中检查self.id,但为时已晚,我在填充字段时想要在管理应用程序中使用这种逻辑。

1 个答案:

答案 0 :(得分:4)

将以下内容(this code的小扩展名)添加到您的admin.py:

from django import forms

class ReadOnlyWidget(forms.Widget):
    def __init__(self, original_value, display_value):
        self.original_value = original_value
        self.display_value = display_value

        super(ReadOnlyWidget, self).__init__()

    def render(self, name, value, attrs=None):
        if self.display_value is not None:
            return unicode(self.display_value)
        return unicode(self.original_value)

    def value_from_datadict(self, data, files, name):
        return self.original_value

class ReadOnlyAdminFields(object):
    def get_form(self, request, obj=None):
        form = super(ReadOnlyAdminFields, self).get_form(request, obj)
        fields = getattr(self, 'readonly', [])
        if obj is not None:
            fields += getattr(self, 'readonly_on_edit', [])

        for field_name in fields:
            if field_name in form.base_fields:
                if hasattr(obj, 'get_%s_display' % field_name):
                    display_value = getattr(obj, 'get_%s_display' % field_name)()
                else:
                    display_value = None

                form.base_fields[field_name].widget = ReadOnlyWidget(getattr(obj, field_name, ''), display_value)
                form.base_fields[field_name].required = False

        return form

然后,您可以在编辑对象时指定某些字段应该只读:

class PersonAdmin(ReadOnlyAdminFields, admin.ModelAdmin):
    readonly_on_edit = ('home',)

admin.site.register(Person, PersonAdmin)