0

I added one model Author in models.py file in my app and created model names for the author while I opened in admin panel it's showing as Author object(12) how can I change that?

I tried to add Unicode

class Author(models.Model):
    author_name=models.CharField(max_length=300)

I want field name instead of Author object in the admin panel. enter image description here below i want change Author Object

  • Override the `__str__()` method in your `Author` class, that's what's used by python 3 when you `print` an object. Make it a habit to always override `__str__` for all your models. – dirkgroten Oct 14 '19 at 10:28
  • Possible duplicate of [Django "xxxxxx Object" display customization in admin action sidebar](https://stackoverflow.com/questions/9336463/django-xxxxxx-object-display-customization-in-admin-action-sidebar) – dirkgroten Oct 14 '19 at 10:30

3 Answers3

2

Try This:

class Author(models.Model):
    author_name=models.CharField(max_length=300)

    def __str__(self):
        return self.author_name

Follow what @dirkgroten said "Make it a habit to always override str for all your models"


Also You can use list_display method in your admin.py to achieve similar result. Create a admin class and use list_display to render fields of model in tabular format

Admin.py

from app.models import Artist      #<-----Import you artist model 

@admin.register(Artist)          #<----- admin class should be just below this line
class ArtistAdmin(admin.ModelAdmin):

    list_display = ["id", "author_name"]

Or you can also do this:

from app.models import Artist      #<-----Import you artist model 


class ArtistAdmin(admin.ModelAdmin):
    list_display = ["id", "author_name"]

admin.site.register(Artist, ArtistAdmin)    #<----register your class also
ans2human
  • 2,300
  • 1
  • 14
  • 29
0

Here is the example of overriding __str__ method for cases like yours.

class Language(models.Model):
    language = models.CharField(max_length=32)

    class Meta:
        app_label = "languages"
        ordering = ["-modified"]

    def __str__(self):
        return f"{self.language} (language {self.id})"
0

You can overrride __str__ method in django model class like that

class Author(models.Model):
    author_name=models.CharField(max_length=300)

    def __str__(self):
        return self.author_name