Django admin - 如果编辑对象,删除字段

时间:2010-05-19 15:23:09

标签: django django-admin

我有一个可以通过Django管理区域访问的模型,如下所示:

# model
class Foo(models.Model):
    field_a = models.CharField(max_length=100)
    field_b = models.CharField(max_length=100)

# admin.py
class FooAdmin(admin.ModelAdmin):
    pass

假设用户正在添加对象,我想显示field_a和field_b,但如果用户正在编辑对象,则只显示field_a。是否有一种简单的方法可以使用fields属性?

如果是这样的话,我可能会破解JavaScript解决方案,但根本不这样做是对的!

2 个答案:

答案 0 :(得分:6)

您可以为管理员创建自定义ModelForm以删除__init__

中的字段
class FooForm(forms.ModelForm):
    class Meta(object):
        model = Foo

    def __init__(self, *args, **kwargs):
        super(FooForm, self).__init__(*args, **kwargs)
        if self.instance and self.instance.pk:
            # Since the pk is set this is not a new instance
            del self.fields['field_b']

class FooAdmin(admin.ModelAdmin):
    form = FooForm

编辑:从John关于将字段设置为只读的注释中提示,您可以将其设置为隐藏字段并覆盖清除以确保值不会更改。

class FooForm(forms.ModelForm):
    class Meta(object):
        model = Foo

    def __init__(self, *args, **kwargs):
        super(FooForm, self).__init__(*args, **kwargs)
        if self.instance and self.instance.pk:
            # Since the pk is set this is not a new instance
            self.fields['field_b'].widget = forms.HiddenInput()

    def clean_field_b(self):
        if self.instance and self.instance.pk:
            return self.instance.field_b
        else:
            return self.cleaned_data['field_b']  

答案 1 :(得分:0)

您还可以执行以下操作

class FooAdmin(admin.ModelAdmin)
    def change_view(self, request, object_id, extra_context=None):       
        self.exclude = ('field_b', )
        return super(SubSectionAdmin, self).change_view(request, object_id, extra_context)

从这里采取Django admin: exclude field on change form only