Django Admin does not use `get_FOO_display`

99 views
Skip to first unread message

Ibrahim Abou Elenein

unread,
Apr 4, 2023, 12:44:28 PM4/4/23
to Django users
I had a model having a field that uses Choices 
    status = FSMField(default=STATUSES.PENDING, choices=STATUSES, protected=True)

I did override  the `get_status_display ` and its effect was not applied in the Django admin  

I looked up Django code and found 
```
def display_for_field(value, field, empty_value_display): from django.contrib.admin.templatetags.admin_list import _boolean_icon if getattr(field, "flatchoices", None): return dict(field.flatchoices).get(value, empty_value_display)
``` I changed it to use get_FOO_display and it worked,
my question is why does it have this behavior? and how in my application can I make use of this?

Thank you.

Opeoluwa Fatunmbi

unread,
Apr 5, 2023, 9:42:24 PM4/5/23
to django...@googlegroups.com

The reason why your overridden get_status_display method is not being applied in the Django admin is because the admin's display_for_field function uses the flatchoices attribute of the field to retrieve the display value of the field's current value.

The flatchoices attribute is a list of two-tuples that represent the choices available for the field, flattened into a single list. The first element of each tuple is the value, and the second element is the display string. The display_for_field function uses the flatchoices list to retrieve the display value of the current value, rather than calling the field's get_FOO_display method.

To make use of your overridden get_status_display method in the admin, you can set the flatchoices attribute of the field to None or remove the attribute altogether. This will cause the admin to call the get_status_display method instead of the display_for_field function.


class MyModelAdmin(admin.ModelAdmin): form = MyModelForm class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Remove the flatchoices attribute of the status field self.fields['status'].flatchoices = None


In this example, we're creating a MyModelForm that is used in the MyModelAdmin. We're overriding the __init__ method of the form to remove the flatchoices attribute of the status field, which will cause the admin to call the get_status_display method instead.











--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/7dabd818-4b70-409e-8af3-482dffffeb3an%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages