Django says my Model is not defined

15,744

Solution 1

Either move the class definition of Country on above User in the file

OR

In the User model, update the attribute country to:

country = models.ForeignKey('Country',null=False) 

Documentation on this can be found here

Solution 2

You need to move the definition of Country above the definition of User.

What is happening is the compiler (when compiling to .pyc byte code) is compiling the Class definition for User and sees a reference to a Country type object. The compiler has not seen this definition yet and does not know what it is, hence the error of it being not defined.

So the basic rule of thumb-> Everything has to be defined before you call or reference it

Share:
15,744
user1659653
Author by

user1659653

Updated on June 14, 2022

Comments

  • user1659653
    user1659653 almost 2 years

    So I´m developing a project using Django and I´m trying to create several relationships between some models such as User and Country. When I try to syncdb my console outputs " Name Country is not defined". Check out the code:

    class User(models.Model):
     name = models.CharField(max_length=50,null=False)
     email = models.EmailField(max_length=50,null=False)
     password = models.CharField(max_length=10,null=False)
     country = models.ForeignKey(Country,null=False) #error here
     rol = models.ForeignKey(Rol,null=False)
     job = models.ManyToManyField(Job) #UserxJob
     skill = models.ManyToManyField(Skill) #UserxSkill
     plan = models.ManyToManyField(Plan) #UserxPlan
     image = models.ForeignKey(Image)
     description = models.TextField(max_length=300)
     website = models.URLField(max_length=100,null=True)
    
     def __unicode__(self):
        return  self.name
    
    
    class Country(models.Model):
     name = models.CharField(max_length=50,null=False)
    
     def __unicode__(self):
        return self.name
    

    Could you please help me out with this one?

  • Paul Renton
    Paul Renton almost 11 years
    No worries. I would go with karthikr's alternative method of using 'Country'. That way you don't have to move things around. I just wanted to explain how the compilation worked :)