Get the object name in django admin

Viewed 63

Hej!

I want to have a category for turnovers in my admin area and in there I have a field with currency. It is a dropdown field with pre given currencies.

My problem is, that there aren't the actual currencies shown rather their IDs. (like Object 123).

Does anyone know how to solve this for an inline?

# models.py

class Currency(models.Model):
    code = models.CharField(max_length=3, unique=True)
    currency = models.CharField(max_length=150, unique=True)


class Turnover(models.Model):
    currency = models.ForeignKey(Currency, on_delete=models.PROTECT)

# admin.py

class TurnoverInline(admin.TabularInline):
    model = Turnover
    extra = 1
    classes = ["collapse"]


class SomeAdmin(admin.ModelAdmin):
    form = SomeForm
    save_on_top = True

    inlines = [
        TurnoverInline
    ]

For a similar problem I created admin.ModelAdmins and integrated a code_str(self) and str(self) method in the model. But those aren't Inlines and in the SomeForm/SomeAdmin as fields/autocomplete_fields.

1 Answers

You can use __str__ in the Currency model:

class Currency(models.Model):
    code = models.CharField(max_length=3, unique=True)
    currency = models.CharField(max_length=150, unique=True)
    
    def __str__(self):
        return f'{self.code} - {self.currency}'

The dropdown should then show this format instead of the object and id.

Related