Prakash Vegiraju
Prakash Vegiraju

Reputation: 89

how to change admin field name in django, python

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

Upvotes: 0

Views: 663

Answers (3)

ans2human
ans2human

Reputation: 2357

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

Upvotes: 2

Mohammed Aadil
Mohammed Aadil

Reputation: 153

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

Upvotes: 0

Ilya Datskevich
Ilya Datskevich

Reputation: 71

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})"

Upvotes: 0

Related Questions