1

我一直在尝试在 django-userena 中编辑用户配置文件,除了我的 ManyToManyFields 之外一切都很好。我设置了以下模型:

class MyProfile(UserenaBaseProfile):
    user = models.OneToOneField(User,unique=True,  
                        verbose_name=_('user'),related_name='my_profile')
    favourite_snack = models.CharField(_('favourite snack'),max_length=5) 
    firstname = models.CharField(_('username'), max_length=55)
    lastname = models.CharField(_('lastname'), max_length=66)
    industry = models.CharField(_('industry'), max_length=190)
    occupation = models.CharField(_('occupation'), max_length=140)
    bio = models.TextField(_('bio'))
    phone = models.CharField(_('phone'), max_length=10)
    skills = models.ManyToManyField(Skills)
    Interests = models.ManyToManyField(Interests)
    website = models.URLField()

class Skills(models.Model):
    skillName = models.CharField(max_length=80)

class Interests(models.Model):
    interestName = models.CharField(max_length=140)

当我同步数据库时,我收到以下错误:

 File "/pathtodjango/bin/app/accounts/models.py", line 17, in MyProfile
    skills = models.ManyToManyField(Skills)
NameError: name 'Skills' is not defined
4

2 回答 2

19

使用惰性引用:

skills = models.ManyToManyField('Skills')
于 2014-06-08T16:06:10.787 回答
4

问题是您Skills在定义模型类之前对其进行了引用。请注意,Python 不像 Javascript 那样进行函数(类)提升。所以你的代码应该是这样的

class Skills(models.Model):
    skillName = models.CharField(max_length=80)

class Interests(models.Model):
    interestName = models.CharField(max_length=140)


class MyProfile(UserenaBaseProfile):
    user = models.OneToOneField(User,unique=True,  
                        verbose_name=_('user'),related_name='my_profile')
    favourite_snack = models.CharField(_('favourite snack'),max_length=5) 
    firstname = models.CharField(_('username'), max_length=55)
    lastname = models.CharField(_('lastname'), max_length=66)
    industry = models.CharField(_('industry'), max_length=190)
    occupation = models.CharField(_('occupation'), max_length=140)
    bio = models.TextField(_('bio'))
    phone = models.CharField(_('phone'), max_length=10)
    skills = models.ManyToManyField(Skills)
    Interests = models.ManyToManyField(Interests)
    website = models.URLField()
于 2014-06-08T16:12:06.253 回答