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)'
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.Also hard refresh through
ctrl+f5
and restart server in another port usingpython manage.py runserver 5000
.Edit
After looking at your GitHub repo, I observed the issue is with naming the model as
User
which is an in-built model in Django indjango.contrib.auth
so kindly change it toCustomUser
and also the problem arises with fieldsfirst_name
andlast_name
as these are also inUser
model so kindly try below model:Then run both the migration commands (makemigrations and migrate).
admin.py
urls.py
Then you can change the fields' name in templates by yourself.