0

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)'

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
  • 1
    Please post the full traceback. – Willem Van Onsem Nov 10 '22 at 18:50
  • Is your question about the `__str__` method, or is it about the `AttributeError` exception? I'm confused. – John Gordon Nov 10 '22 at 18:58
  • 2
    Some problem can also be with migration files, kindly check it. – Sunderam Dubey Nov 10 '22 at 19:16
  • JonhGordon my doubt is about the AtributteError, I'm not understanding why is that occuring SunderamDubey, I try a lot of times to make the makemigrations and migrate codes but didn't resolve WillemVanOnsem, please check the entire error bellow Thank you for now guys – Vitor Anghében Nov 16 '22 at 18:35
  • AttributeError at /admin/crud_app/user/ 'User' object has no attribute 'first_name' Request Method: GET Request URL: http://127.0.0.1:8000/admin/crud_app/user/ Django Version: 4.1.3 Exception Type: AttributeError Exception Value: 'User' object has no attribute 'first_name' Exception Location: D:\One Drive\One Drive ANG\OneDrive - ANG\Arquivos Vitor\curso_de_programacao\conquiste_sua_vaga\CRUD\crud_app\models.py, line 15, in __str__ Raised during: django.contrib.admin.options.changelist_view Python Executable: C:\Users\vitor\AppData\Local\Programs\Python\Python310\python.exe – Vitor Anghében Nov 16 '22 at 18:37

2 Answers2

2

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.

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 in django.contrib.auth so kindly change it to CustomUser and also the problem arises with fields first_name and last_name as these are also in User model so kindly try below model:

from django.db import models


class CustomUser(models.Model):
    """
    A normal class that represents a User object, the attributes are those bellow:
    """
    f_name = models.CharField(
        verbose_name="First Name", max_length=30, default="Test")
    l_name = models.CharField(
        verbose_name="Last Name", max_length=30, default='Test')
    cpf = models.CharField(verbose_name="CPF", max_length=15)
    age = models.IntegerField(verbose_name="Age")
    email = models.EmailField(verbose_name="email", max_length=30)

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

Then run both the migration commands (makemigrations and migrate).

admin.py

from django.contrib import admin
from .models import CustomUser


@admin.register(CustomUser)
class CustomUserAdmin(admin.ModelAdmin):
    list_display = ['id', 'f_name', 'l_name', 'cpf', 'age', 'email']

urls.py

from django.urls import path
from crud_app.views import update_user, check_user, delete_user, register_user, menu

urlpatterns = [
    path('', menu),
    path("check_user/", check_user, name="check_user.html"),
    path("register_user/", register_user, name="register_user.html"),
    path("update_user/", update_user, name="update_user.html"),
    path("delete_user/", delete_user, name="delete_user.html")
]

Then you can change the fields' name in templates by yourself.

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
  • That is not the problem, I try and the problem persists The django version is the 4.1.2 – Vitor Anghében Nov 12 '22 at 21:33
  • 1
    @VitorAnghében Share the GitHub repo, will check the issue and soon come to you. – Sunderam Dubey Nov 12 '22 at 21:37
  • Sure man, thank you for now! https://github.com/angheben/CRUD_Django – Vitor Anghében Nov 14 '22 at 23:08
  • did you find why this is occuring man? I'm really stucked on that – Vitor Anghében Nov 16 '22 at 20:27
  • 1
    I see man, I would never discover that hahaha The problem has been solved but another one appear 'OperationalError at /admin/crud_app/customuser/ no such table: crud_app_customuser' For you, this problem also appered? Anyway I mark as resolved and I appreciate very much your help man, if you come to Brazil some day I will pay you a beer! Hahaha – Vitor Anghében Nov 17 '22 at 18:02
  • @VitorAnghében Have you deleted any of the migration files? – Sunderam Dubey Nov 17 '22 at 18:04
  • Yes I deleted all my migrations and run the makeimgrations and migrate, more then once to be sure. To upvote it's just mark the up arrow right? – Vitor Anghében Nov 17 '22 at 18:14
  • 1
    @VitorAnghében yes you can click on up arrow. Have you deleted the database? You should also delete that. Then it will work properly. – Sunderam Dubey Nov 17 '22 at 18:16
  • @VitorAnghében Currently the thing you can do again delete the database file and migration files then again run migrate commands, the problem arose because you only deleted migration files but in the actual database the `User` model still exists that's why it says no such table as `CustomUser` hope you understood. The moment you again create fresh database with new migration files it would have `CustomUser` model instead of `User` model. – Sunderam Dubey Nov 17 '22 at 18:22
  • Right right, now I did it @Sunderam Dubey, man, I try it excluding the migrations file and runing the makemigrations and migrate again, but the problem persists, the problem is occuring in this part of the code -> return Database.Cursor.execute(self, query, params) – Vitor Anghében Nov 17 '22 at 18:58
  • 1
    Now it worked, I needed to run this code to work python manage.py migrate --run-syncdb, once more @Sunderam Dubey, thank you very much man!! – Vitor Anghében Nov 17 '22 at 19:00
  • man I'm facing the same problem in another project, I try do apply all those steps and I'm reciving exactly the same problem __str__ function not working, in this project my class is called Beer, so I think the problem it's not in the name of my class, take a look in this repositorie bellow and let me know if this problem is occouring in your computer to please! https://github.com/angheben/Beer_Tap_Dispenser_API By the way, I upvoted your answers friend :D Once more, I appreciate your time! – Vitor Anghében Nov 18 '22 at 13:11
  • @VitorAnghében Will check it soon :) currently busy in some another project has to submit until tomorrow. – Sunderam Dubey Nov 19 '22 at 14:11
  • Sure, take your time – Vitor Anghében Nov 19 '22 at 14:17
  • I appreciate very much your help so far but I took it off the accepted answer, I'm was facing the same problem in diferent projects and looks like not to be necessary anymore to use that str function, Django is already puting the atributes automatically, if you want to edit your answer to that I'll put it again ok? Just to help other people if they face this problem And please, if you can check if it's working for you to, just to be sure – Vitor Anghében Nov 29 '22 at 22:29
  • Extremely sorry, I forgot to see the repo, you should have replied earlier, but now I'd be able to see the repo after 3-4 days as currently I have [eye flu](https://en.m.wikipedia.org/wiki/Conjunctivitis), will see soon. – Sunderam Dubey Nov 30 '22 at 05:05
  • No problem @Sunderam Dubey, when you're be better you take a look, and I hope you get better soon of this eye flu man! – Vitor Anghében Dec 01 '22 at 11:15
0

You need to correct verbose_name instead of name of model fields like this.

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

    def __str__(self):
        return self.first_name
Parth Mehta
  • 191
  • 6
  • Parth Mehta, I try it but the problem persist Look like to be a problem in django dependencies, every one that I talk told me that is working normally, really strange – Vitor Anghében Nov 15 '22 at 21:20
  • Then first of all uninstall django and install django once then delete migrations files and do makemigrations and migrate once – Parth Mehta Nov 16 '22 at 04:56
  • I try it and was not succesfull I try in three different projects, uninstalling and installing again, in different virtual enviroments too and still didn't work – Vitor Anghében Nov 16 '22 at 22:33