8👍
use a form field
somefield = forms.CharField(
widget=forms.TextInput(attrs={'readonly':'readonly'})
)
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:
-
do not add the name of your
TextField
to thereadonly_fields
in yourModelAdmin
subclass (otherwise step 2 has no effect) -
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
.
- [Django]-Django User M2M relationship
- [Django]-ElasticSearch term suggest on analyzed field returns no suggestions
- [Django]-Appending a queryset to a list/tuple without evaluating it
- [Django]-Group by in django
- [Django]-Convert python object to protocol buffer object
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
.
- [Django]-Model inheritance in django-nonrel on app engine
- [Django]-Django objects being "non subscriptable" leads me to write redundant code
- [Django]-Django set multiple allowed hosts
- [Django]-DRF – ModelSerializer with a non-model write_only field
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
.
- [Django]-How to dynamically make an existing non-abstract django model, abstract?
- [Django]-How to serialize recursive relationship with self in Django REST Framework?