Django admin:如何显示模型中标记为editable=False的字段?

时间:2021-10-29 05:58:12

Even though a field is marked as 'editable=False' in the model, I would like the admin page to display it. Currently it hides the field altogether.. How can this be achieved ?

即使一个字段在模型中被标记为“editable=False”,我还是希望管理页面显示它。目前它完全隐藏了这个领域。如何实现这一点?

2 个解决方案

#1


141  

Use Readonly Fields. Like so (for django >= 1.2):

使用只读的字段。(对于django >= 1.2):

class MyModelAdmin(admin.ModelAdmin):
    readonly_fields=('first',)

#2


14  

Update

更新

This solution is useful if you want to keep the field editable in Admin but non-editable everywhere else. If you want to keep the field non-editable throughout then @Till Backhaus' answer is the better option.

如果您希望在Admin中保持字段可编辑,但在其他任何地方都不可编辑,那么这个解决方案是非常有用的。如果你想让整个字段不可编辑,那么@Till Backhaus的答案是更好的选择。

Original Answer

原来的答案

One way to do this would be to use a custom ModelForm in admin. This form can override the required field to make it editable. Thereby you retain editable=False everywhere else but Admin. For e.g. (tested with Django 1.2.3)

一种方法是在admin中使用自定义的ModelForm。此表单可以覆盖所需字段,使其可编辑。因此,除了Admin之外,其他地方都保留editable=False。例如(用Django 1.2.3测试)

# models.py
class FooModel(models.Model):
    first = models.CharField(max_length = 255, editable = False)
    second  = models.CharField(max_length = 255)

    def __unicode__(self):
        return "{0} {1}".format(self.first, self.second)

# admin.py
class CustomFooForm(forms.ModelForm):
    first = forms.CharField()

    class Meta:
        model = FooModel
        fields = ('second',)

class FooAdmin(admin.ModelAdmin):
    form = CustomFooForm

admin.site.register(FooModel, FooAdmin)

#1


141  

Use Readonly Fields. Like so (for django >= 1.2):

使用只读的字段。(对于django >= 1.2):

class MyModelAdmin(admin.ModelAdmin):
    readonly_fields=('first',)

#2


14  

Update

更新

This solution is useful if you want to keep the field editable in Admin but non-editable everywhere else. If you want to keep the field non-editable throughout then @Till Backhaus' answer is the better option.

如果您希望在Admin中保持字段可编辑,但在其他任何地方都不可编辑,那么这个解决方案是非常有用的。如果你想让整个字段不可编辑,那么@Till Backhaus的答案是更好的选择。

Original Answer

原来的答案

One way to do this would be to use a custom ModelForm in admin. This form can override the required field to make it editable. Thereby you retain editable=False everywhere else but Admin. For e.g. (tested with Django 1.2.3)

一种方法是在admin中使用自定义的ModelForm。此表单可以覆盖所需字段,使其可编辑。因此,除了Admin之外,其他地方都保留editable=False。例如(用Django 1.2.3测试)

# models.py
class FooModel(models.Model):
    first = models.CharField(max_length = 255, editable = False)
    second  = models.CharField(max_length = 255)

    def __unicode__(self):
        return "{0} {1}".format(self.first, self.second)

# admin.py
class CustomFooForm(forms.ModelForm):
    first = forms.CharField()

    class Meta:
        model = FooModel
        fields = ('second',)

class FooAdmin(admin.ModelAdmin):
    form = CustomFooForm

admin.site.register(FooModel, FooAdmin)