Name of the object not coming in Django admin

I’ve included str but name & price not showing in admin
Instead Item Model Object (2)
“” “” “” (1) & so on is coming.
Where is the error

from django.db import models

# Create your models here.

class ItemModel(models.Model):
    id = models.IntegerField(primary_key = True)
    name = models.CharField(max_length = 80,blank = False)
    price = models.FloatField()

class Meta:
    ordering = ['name']

    def __str__(self):
	    return f"{self.name}:{self.price}"

Is your identation correct?
In the provided code, there’s 2 classes: ItemModel and Meta. The __str__ method is inside the Meta.

Normally you would have this like:

from django.db import models

# Create your models here.

class ItemModel(models.Model):
    id = models.IntegerField(primary_key = True)
    name = models.CharField(max_length = 80,blank = False)
    price = models.FloatField()

    class Meta:
        ordering = ['name']

    def __str__(self):
	    return f"{self.name}:{self.price}"
2 Likes

Have the same issue. The important thing that def str need to be after class Meta %)

No. There’s no such constraint. The only important thing is that the __str__ method is defined at the class “body”, or within the same number of tab/spaces as the fields. The above example, is just the django style convention for model definitions, there is:

class ItemModel(models.Model):
    # Fields go first
    id = models.IntegerField(primary_key = True)
    name = models.CharField(max_length = 80,blank = False)
    price = models.FloatField()

    # then the Meta class, if any
    class Meta:
        ordering = ['name']

    # then instance methods, like __str__
    def __str__(self):
	    return f"{self.name}:{self.price}"