Django admin: How to display a field that is marked as editable=False' in the model?

前端 未结 3 2072
鱼传尺愫
鱼传尺愫 2020-11-28 22:36

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 t

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 22:46

    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.

    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)

    # 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)
    

提交回复
热议问题