Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Admin showing Object - not working with __unicode__ OR __str__

my Django admin panel is showing object instead of self.name of the object.

I went through several similar questions here yet couldn't seem to resolve this issue. __unicode__ and __str__ bear the same results, both for books and for authors. I've changed those lines and added new authors/books in every change but no change.

MODELS.PY

from django.db import models
from django.contrib.auth.models import User


# Create your models here.

class Author(models.Model):
    name = models.CharField(max_length=100)


def __str__(self):
    return self.name


class Book(models.Model):
    auto_increment_id = models.AutoField(primary_key=True)
    name = models.CharField('Book name', max_length=100)
    author = models.ForeignKey(Author, blank=False, null=False)
    contents = models.TextField('Contents', blank=False, null=False)


def __unicode__(self):
    return self.name

I used both unicode & str interchangeably, same result.

Here are the screenshots of the admin panel by menu/action.

1st screen

1st screen

Author List

Author List

Single Author

Single Author

like image 970
clusterBuddy Avatar asked Dec 19 '22 14:12

clusterBuddy


1 Answers

Your indentation is incorrect. You need to indent the code to make it a method of your model. It should be:

class Author(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

If you are using Python 3, use __str__. If you are using Python 2, use __unicode__, or decorate your class with the python_2_unicode_compatible decorator. After changing the code, make sure you restart the server so that code changes take effect.

like image 150
Alasdair Avatar answered May 19 '23 17:05

Alasdair