Login

convenience parent class for UserProfile model

Author:
willhardy
Posted:
April 28, 2009
Language:
Python
Version:
1.0
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. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.