Doesn't "__str__()" work properly in "admin.py" for Django Admin?

83 Views Asked by At

For example, I define __str__() in Person model as shown below:

# "models.py"

from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=20)
    
    def __str__(self): # Here
        return self.first_name + " " + self.last_name

Then, I define Person admin as shown below:

# "admin.py"

from django.contrib import admin
from .models import Person

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
    pass

Then, the full name is displayed in the message and list in "Change List" page:

enter image description here

But, when I define __str__() in Person admin as shown below:

# "admin.py"

from django.contrib import admin
from .models import Person

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):

    def __str__(self): # Here
        return self.first_name + " " + self.last_name

Or, when I define __str__() then assign it to list_display in Person admin as shown below:

# "admin.py"

from django.contrib import admin
from .models import Person

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
    list_display = ('__str__',) # Here

    def __str__(self): # Here
        return self.first_name + " " + self.last_name

The full name is not displayed in the message and list in "Change List" page:

enter image description here

So, doesn't __str__() work properly in Person admin?

1

There are 1 best solutions below

0
whoami On

list_display will lookup field based on model._meta. All class has their own __str__ method, includes your model class which is Person. So list_display will use __str__ method provided by your model class, even you don't implement it in your model class, it will provide the default implementation of __str__. Hence list_display show like what you got. On the other hand, list_display default value is ("__str__",) equal to what you do above. Here is other approach which might work

admin.py

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
    list_display = ('whatever',) # Here

    def whatever(self, obj): # Here
        return obj.first_name + " " + obj.last_name