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

前端 未结 3 2062
鱼传尺愫
鱼传尺愫 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)
    
    0 讨论(0)
  • 2020-11-28 22:53

    Your read-only fields must be in fields also:

    fields = ['title', 'author', 'content', 'published_date', 'updated_date', 'created_date']
    readonly_fields = ('published_date', 'updated_date', 'created_date')
    
    0 讨论(0)
  • 2020-11-28 23:02

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

    class MyModelAdmin(admin.ModelAdmin):
        readonly_fields=('first',)
    
    0 讨论(0)
提交回复
热议问题