I am learning django, here is the model i have created

class UserProfile(models.Model):
    name = models.CharField(max_length=50, verbose_name="Name")
    login = models.CharField(max_length=25, verbose_name="Login")
    password = models.CharField(max_length=100, verbose_name="Password")
    phone = models.CharField(max_length=20, verbose_name="Phone number")

    def __str__ (self):
        return self.name

Since name is a static variable, so in method __str__, it can also be called like this

    def __str__ (self):
        return UserProfile.name

But when i tried to access variable using the above method , i get the following error

AttributeError at /admin/TasksManager/userprofile/
type object 'UserProfile' has no attribute 'name'
Request Method: GET
Request URL:
Django Version: 1.6
Exception Type: AttributeError
Exception Value:    
type object 'UserProfile' has no attribute 'name'
Exception Location: C:\Users\X\django_book\Work_manager\TasksManager\models.py in __str__, line 18
Python Executable:  C:\Users\X\django_book\Scripts\python.EXE
Python Version: 3.4.3
Python Path:    
Server time:    Thu, 7 Jan 2016 23:10:34 +0530

Why so ??

I applied the same technique in the following class, where it works perfectly fine

class Rect:

    status = "this is test"

    def __init__(self, l, b):
        self.l = l
        self.b = b

    def something(self):
        return Rect.status

Why there is a contradiction ?

I know very little about django, but obviously it is a part of the ORM magic. You could try

return str(UserProfile._meta.get_field('name'))


It is a strange way to define __str__() anyway, because __str__() is typically an instance method.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.