About Errors at Read-only Methods in Administration

In Django administration, read-only fields may list methods or properties of the model or model admin. However, if an AttributeError, ValueError, or ObjectDoesNotExist exceptions are raised, the field will just show "-" as the value. Thats not practical for debugging. But you can re-raise the error with a custom decorator:

Put this decorator into myproject/apps/core/admin.py:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
from functools import wraps

class ReadonlyFieldError(Exception):
    pass

def catch_field_exception(func):
    @wraps(func)
    def wrapped_func(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            raise ReadonlyFieldError(
                'Exception occurred while processing Admin field "{}": {}'.format(
                    func.__name__, str(e)
                )
            ) from e

    return wrapped_func

Then use it for display methods in the admin.py files:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
from django.contrib import admin
from django.utils.html import mark_safe
from django.utils.translation import gettext_lazy as _
from myproject.apps.core.admin import catch_field_exception
from .models import Post

@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
    readonly_fields = ["show_preview"]

    @catch_field_exception
    @admin.display(description=_("Preview"))
    def show_preview(self, obj):
        html = ...
        return mark_safe(html)

Tips and Tricks Programming Development Django 4.2 Django 3.2