About Readonly Fields in Django Administration
Django administration tip: if you want to show a field with editable=False
attribute or the results of a model method in the admin form, add the field or the method name to the readonly_fields
list.
from django.contrib import admin
from .models import Post
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
fields = ["created_at", "title", "content", "get_word_count"]
readonly_fields = ["created_at", "get_word_count"]
@admin.display(description="Word Count")
def get_word_count(self, obj):
return len(obj.content.split())
Tips and Tricks Programming Django 5.x Django 4.2 Django 3.2
Also by me
Django Paddle Subscriptions app
For Django-based SaaS projects.
Django GDPR Cookie Consent app
For Django websites that use cookies.