0

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:    http://127.0.0.1:8000/admin/TasksManager/userprofile/
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:    
['C:\\Users\\X\\django_book\\Work_manager',
 'C:\\Windows\\system32\\python34.zip',
 'C:\\Users\\X\\django_book\\DLLs',
 'C:\\Users\\X\\django_book\\lib',
 'C:\\Users\\X\\django_book\\Scripts',
 'C:\\Python34\\Lib',
 'C:\\Python34\\DLLs',
 'C:\\Users\\X\\django_book',
 'C:\\Users\\X\\django_book\\lib\\site-packages']
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 ?

0

1 Answer 1

0

The Django model does not contain static variables. They are used by the metaclass to define actual instance variables. You can't access them through the class.

Sign up to request clarification or add additional context in comments.

5 Comments

So how can i acheive the same thing in class Rect ?
There is a lot of metaclass trickery that goes on to make this possible in Django; it's not something you can just enable.
I don't really understand what you want to achieve.
Just for learning purpose nothing else

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.