John
John

Reputation: 1360

django user profile database problem

I have app called aaa and in models.py in aaa i have sth like:

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)

I add to my setting.py

AUTH_PROFILE_MODULE = 'aaa.BBB'

then i go to django shell and type

>>> 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.

Some body have idea what is wrong? Edit: I do manage.py syncdb

Upvotes: 3

Views: 1722

Answers (2)

http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users

The method get_profile() does not create the profile, if it does not exist. You need to register a handler for the signal django.db.models.signals.post_save on the User model, and, in the handler, if created=True, create the associated user profile.

The signal they mention is not really documented django-style where they provide code examples, so I will create an example for you:

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)

Upvotes: 7

Filip Dupanović
Filip Dupanović

Reputation: 33670

That's ok, everything works. DoesNotExist: BBB matching query does not exist. means there is no BBB (user profile) for this user (matching query, i.e. get me the user profile for this user).

Use the DoesNotExist exception to assert whether a particular user has an associated user profile. When you create a BBB instance which is related to user a, you won't get a DoesNotExist exception.

Upvotes: 1

Related Questions