Home > Software engineering >  Why django admin is not reading the __str__ method?
Why django admin is not reading the __str__ method?

Time:11-11

I'm trying to add a str method in my models.py file to my administrative page show me the objects I've register with their own name and not like a 'UserObject(1)'

But when I add this method that's what is happening:

AttributeError at /admin/crud_app/user/ 'User' object has no attribute 'first_name'

models.py ->

from django.db import models


class User(models.Model):
    """
    A normal class that represents an User object, the attributes are those bellow:
    """
    first_name = models.CharField(name="First Name", max_length=30)
    last_name = models.CharField(name="Last Name", max_length=30)
    cpf = models.CharField(name="CPF", max_length=30)
    age = models.IntegerField(name="Age")
    email = models.EmailField(name="email", max_length=30)

    def __str__(self):
        return self.first_name
    

admin.py ->

from django.contrib import admin
from .models import User

admin.site.register(User)

I try to add the str method and I'm was expecting to recive the name that I give to my object registered instead of 'Name object(1)'

CodePudding user response:

You should define it in f-strings to take care of None values so that if it is None so it will not raise error.

class User(models.Model):
    """
    A normal class that represents an User object, the attributes are those bellow:
    """
    first_name = models.CharField(name="First Name", max_length=30)
    last_name = models.CharField(name="Last Name", max_length=30)
    cpf = models.CharField(name="CPF", max_length=30)
    age = models.IntegerField(name="Age")
    email = models.EmailField(name="email", max_length=30)

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

Also hard refresh through ctrl f5 and restart server in another port using python manage.py runserver 5000.

CodePudding user response:

  • Make sure there is no extra spaces before "def", after model fields.

  • Use f-strings if normal self.first_name is not working. e.g f"{self.first_name}"

By the way, it is working perfectly for me on all of my project. Which django version you are using?

  • Related