2

I initially extended only the Group model, and although I got the extra fields working correctly, I end up with inconsistent results when I switch back to the auth-user model:

group1 = MyGroup(..)
user = group1.user_set.all()[0]
group2 = user.groups.all()[0]
group1 == group2 #(False!)
type(group1) #MyGroup..
type(group2) #Group..

My next thought was to extend both the auth.User and auth.Group models.

Example structure:

from django.contrib.auth.models import User As DjangoUser
from django.contrib.auth.models import Group As DjangoGroup

class MyGroup(DjangoGroup):
    extra1 = models.CharField(..)

class MyUser(DjangoUser):
    extra1 = models.CharField(..)

Is this possible? I saw a bug-report stating it was fixed here. However I didn't see an example of the correct way to achieve this, nor was it clear if this portion was necessary post bug-fix:

manager = UserManager()
class MyUser(DjangoUser):
    signature = forms.CharField()
    post_count = forms.IntegerField()
    objects = manager
    _default_manager = manager

Any ideas/examples of this sort of behavior? I attempted to re-define the 'groups' link in the user model but that led to a validation error. Ideally I would like to be able to run the example above and have group1 == group2 and type(group2) == type(MyGroup())

steve-gregory
  • 7,396
  • 8
  • 39
  • 47
  • May be this could help http://stackoverflow.com/questions/4827965/can-i-change-djangos-auth-user-username-field-to-be-100-chars-long-without-brea – Rohan Aug 22 '12 at 05:39

1 Answers1

0

You can dynamically add a new field to django User/Group models, so that no new class type will be created. For reference, see: http://code.google.com/p/comaie-django-groups/source/browse/trunk/src/comaie/django/groups/models.py?r=5

models.ForeignKey(
    Group,
    null            = True,
    blank           = True,
    related_name    = 'children',
    verbose_name    = _('parent'),
    help_text       = _('The group\'s parent group. None, if it is a root node.')
).contribute_to_class(Group, 'parent')

def get_all_groups(self):
    """
    Returns all groups the user is member of AND all parent groups of those
    groups.
    """
    direct_groups = self.groups.all()
    groups = set()

    for group in direct_groups:
        ancestors = group.get_ancestors().all()
        for anc in ancestors:
            groups.add(anc)
        groups.add(group)

    return groups

setattr(User, 'get_all_groups', get_all_groups)

Congbin Guo
  • 1,685
  • 2
  • 16
  • 16