我有一个名为aaa的应用程序,在aaa的models.py中我喜欢:
from django.db import models
from django.contrib.auth.models import User
class BBB(models.Model):
user = models.OneToOneField(User)
newsletter=models.BooleanField(default=False)
我添加到我的setting.py
AUTH_PROFILE_MODULE = 'aaa.BBB'
然后我去django shell并输入
>>> from django.contrib.auth.models import User
>>> a=User.objects.get(id=1)
>>> a.get_profile()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python2.6/dist-packages/Django-1.2.5-py2.6.egg/django/contrib/auth/models.py", line 373, in get_profile
self._profile_cache = model._default_manager.using(self._state.db).get(user__id__exact=self.id)
File "/usr/local/lib/python2.6/dist-packages/Django-1.2.5-py2.6.egg/django/db/models/query.py", line 347, in get
% self.model._meta.object_name)
DoesNotExist: BBB matching query does not exist.
有些人知道出了什么问题吗?
编辑:我做manage.py syncdb
答案 0 :(得分:7)
http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users
方法get_profile()没有 创建配置文件,如果没有 存在。您需要注册一个处理程序 对于信号 django.db.models.signals.post_save on 用户模型,以及在处理程序中 如果created = True,则创建关联的 用户个人资料。
他们提到的信号并没有真正记录在他们提供代码示例的django风格,所以我将为您创建一个示例:
from django.db.models import signals
from django.contrib.auth.models import User
def create_userprofile(sender, **kwargs):
created = kwargs['created'] # object created or just saved?
if created:
BBB.objects.create(user=kwargs['instance']) # instance is the user
# create a BBB "profile" for your user upon creation.
# now every time a user is created, a BBB profile will exist too.
# user.BBB or user.get_profile() will always return something
signals.post_save.connect(create_userprofile, sender=User)
答案 1 :(得分:1)
没关系,一切正常。 DoesNotExist: BBB matching query does not exist.
表示此用户没有BBB(用户个人资料)(匹配查询,即获取此用户的用户个人资料)。
使用DoesNotExist
例外来断言特定用户是否具有关联的用户个人资料。当您创建与用户BBB
相关的a
实例时,您将不会获得DoesNotExist
例外。