Login

convenience parent class for UserProfile model

Author:
willhardy
Posted:
April 28, 2009
Language:
Python
Version:
1.0
Tags:
userprofile
Score:
1 (after 1 ratings)

This is just a reusable convenience parent class to allow you to create and administer an automatic user profile class using the following code:

class UserProfile(UserProfileModel):
    likes_kittens = models.BooleanField(default=True)

Whenever a User object is created, a corresponding UserProfile will also be created. That's it.

NB: You will still need to set AUTH_PROFILE_MODULE in your settings :-)

(PS: It would also be nice to have the resulting class proxy the User object's attributes like django's model inheritance does, while still automatically creating a UserProfile object when a User object is created :-)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.db.models.base import ModelBase
from django.db import models

class _UserProfileModelBase(ModelBase):
    # _prepare is not part of the public API and may change
    def _prepare(cls):
        super(_UserProfileModelBase, cls)._prepare()

        def add_profile(sender, instance, created, **kwargs):
            if created:
                cls.objects.create(user=instance)

        # Automatically link profile when a new user is created
        post_save.connect(add_profile, sender=User, weak=False)

class UserProfileModel(models.Model):
    __metaclass__ = _UserProfileModelBase
    user = models.OneToOneField(User, primary_key=True, parent_link=True)

    class Meta:
        abstract = True

More like this

  1. Improved User Admin by gregb 5 years ago
  2. Alternative to User.get_profile() by jpwatts 7 years, 2 months ago
  3. Creator/updater fields for admin by baumer1122 6 years, 10 months ago
  4. Multiple User subclasses custom Auth backend by ungenio41 3 years, 8 months ago
  5. change settings locally in an individual test by akaihola 4 years, 9 months ago

Comments

Please login first before commenting.