Devone
Devone

Reputation: 175

How to add admin custom field using a method

I'm following the example in Django admin site list_display custom method and I'm getting an error 'colored_name() takes exactly 1 argument (2 given)', what is the issue?

class Person(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    color_code = models.CharField(max_length=6)

def colored_name(self):
    return format_html(
        '<span style="color: #{};">{} {}</span>',
        self.color_code,
        self.first_name,
        self.last_name,
    )

class PersonAdmin(admin.ModelAdmin):
    list_display = ('first_name', 'last_name', 'colored_name')

Upvotes: 0

Views: 87

Answers (1)

levi
levi

Reputation: 22697

You should define colored_name inside PersonAdmin class not Person Model, because it's a method used for the admin panel. Also, it receives an obj argument representing the person instance.

class PersonAdmin(admin.ModelAdmin):
    list_display = ('first_name', 'last_name', 'colored_name')

    def colored_name(self, obj):
        return format_html(
            '<span style="color: #{};">{} {}</span>',
            obj.color_code,
            obj.first_name,
            obj.last_name,
         )

Upvotes: 1

Related Questions