why my "def __str__(self)" function isn't working in django

Viewed 1972
from django.db import models

# Create your models here.
class Article(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField()
    body = models.TextField()
    date = models.DateTimeField(auto_now_add=True)


***def __str__(self):
    return self.title***

when i enter Article.objects.all() this line, after that it should show titles i have in my database. But why it's just showing <Article: Article object> ? although I have written def __str__(self): properly.

InteractiveConsole

3 Answers

Indentation is the fault it seems. I am ignoring those asterisks here because they should not be there. Make sure that your function is inside the Article class with correct indentation.

from django.db import models

class Article(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField()
    body = models.TextField()
    date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

Here's the console output:

(InteractiveConsole)
>>> from about.models import Article
>>> Article.objects.all()
<QuerySet [<Article: This is article 1>, <Article: This is article 2>, <Article: This is article 3>]>

I had also this error But I can solve it .

The way is

  1. Enter text editor and open your model.py file
  2. Point on your line where the function start with "def"
  3. And then back to upper code line end
  4. And then enter

The spaces between class codes and function codes cause this error type. If you want to know , type again "python manage.py makemigrations " and "python manage.py migrate" . You will see that error messages with the end with " def str(self): ^ IndentationError: unindent does not match any outer indentation level"

if you type command "python manage.py runserver" , You will see that error messages with the end with "No uninstalled app label with 'admin'.

Showing back different error messages, However, you can solve this error by doing my steps.

you need to define __repr__ instead

Related