[Django]-How to make a Django admin readonly textarea field

8👍

use a form field

   somefield = forms.CharField(
       widget=forms.TextInput(attrs={'readonly':'readonly'})
    )
👤cinoch

3👍

A bit late, but here’s an idea (inspired by @cinoch`s answer and this answer) that does the trick for me, with a minimum of code:

  1. do not add the name of your TextField to the readonly_fields in your ModelAdmin subclass (otherwise step 2 has no effect)

  2. instead, do add the following to your ModelAdmin subclass:

    formfield_overrides = {
        TextField: dict(widget=Textarea(attrs=dict(readonly=True)))
    }
    

Note this requires some imports:

from django.db.models import TextField
from django.forms import Textarea

The TextField will now show up on the admin page as a scrollable Textarea instead of plain text, and its content will now be read-only, as desired.

Downside is that this applies to all TextFields in the model. If that’s a problem, you should probably use a custom form as suggested by @cinoch and described in more detail here or here.

Also, this has no effect if ModelAdmin.has_change_permission() returns False.

👤djvg

2👍

@alasdair’s answer is actually quite clever, but, unfortunately, it does not provide an example.

Here’s my attempt to clarify, based on the docs for readonly_fields.

Assuming a model like so:

class MyModel(models.Model):
    my_textfield = models.TextField()

The admin could look like this, using format_html to create a readonly textarea:

class MyModelAdmin(admin.ModelAdmin):
    exclude = ['my_textfield']
    readonly_fields = ['display_my_textfield']
    
    @admin.display(description='my textfield')
    def display_my_textfield(self, obj):
        return format_html(
            '<textarea cols="40" rows="10" readonly>{}</textarea>',
            obj.my_textfield)

This also works if ModelAdmin.has_change_permission() returns False.

👤djvg

1👍

The readonly_fields can take method names as well as field names. You could write a method that renders the value of the field in a disabled textarea.

Make sure you exclude the field from the model admin, since it will no longer be in readonly_fields.

Leave a comment