Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Role profiles using multi-table inheritance.

  • Loading branch information...
commit 76ccdff8121acccebe2f1fa3de61e7b0d86dbd2c 1 parent 986d32b
Tom Christie tomchristie authored
1  testproject/urls.py
View
@@ -1,5 +1,6 @@
from django.conf.urls import patterns, include, url
+
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
9 userroles/__init__.py
View
@@ -43,15 +43,6 @@ def roles_dict(self):
if isinstance(item, basestring):
# An item like 'manager'
self._roles_dict[item] = None
- elif len(item) == 2:
- # An item like ('manager', 'myapp.models.ManagerProfile')
- # or ('manager', '')
- name, profile = item
- try:
- profile_class = _import_class_from_string(profile)
- except:
- raise ImproperlyConfigured(_IMPORT_FAILED, profile)
- self._roles_dict[name] = profile_class
else:
# Anything else
raise ImproperlyConfigured(_INCORRECT_ARGS)
50 userroles/models.py
View
@@ -1,6 +1,4 @@
from django.contrib.auth.models import User
-from django.contrib.contenttypes.models import ContentType
-from django.contrib.contenttypes import generic
from django.db import models
from userroles import roles
@@ -8,45 +6,47 @@
class UserRole(models.Model):
user = models.OneToOneField(User, related_name='role')
name = models.CharField(max_length=100, choices=roles.choices)
- content_type = models.ForeignKey(ContentType, null=True, blank=True)
- object_id = models.PositiveIntegerField(null=True, blank=True)
- profile = generic.GenericForeignKey('content_type', 'object_id')
- valid_roles = roles
+ child = models.CharField(max_length=100, blank=True)
+ _valid_roles = roles
+
+ @property
+ def profile(self):
+ if not self.child:
+ return None
+ return getattr(self, self.child)
def __eq__(self, other):
return self.name == other.name
def __getattr__(self, name):
if name.startswith('is_'):
- role = getattr(self.valid_roles, name[3:], None)
+ role = getattr(self._valid_roles, name[3:], None)
if role:
return self == role
raise AttributeError("'%s' object has no attribute '%s'" %
- (self.__class__.__name__, name))
+ (self.__class__.__name__, name))
def __unicode__(self):
return self.name
def set_user_role(user, role, profile=None):
- profile_class = UserRole.valid_roles.roles_dict[role.name]
-
- if profile_class and not profile:
- raise ValueError("You must set a profile for '%s' role" % role.name)
- elif profile and not profile_class:
- raise ValueError("Cannot set a profile for '%s' role" % role.name)
- elif profile and not isinstance(profile, profile_class):
- raise ValueError("Incorrect profile for '%s' role" % role.name)
-
if profile:
- profile.save()
+ try:
+ UserRole.objects.get(user=user).delete()
+ except UserRole.DoesNotExist:
+ pass
+ profile.user = user
+ profile.name = role.name
+ profile.child = str(profile.__class__.__name__).lower()
- try:
- role_obj = UserRole.objects.get(user=user)
- except UserRole.DoesNotExist:
- role_obj = UserRole(user=user, name=role.name)
else:
- role_obj.name = role.name
- role_obj.profile = profile
- role_obj.save()
+ try:
+ profile = UserRole.objects.get(user=user)
+ except UserRole.DoesNotExist:
+ profile = UserRole(user=user, name=role.name)
+ else:
+ profile.name = role.name
+
+ profile.save()
3  userroles/testapp/models.py
View
@@ -1,5 +1,6 @@
from django.db import models
+from userroles.models import UserRole
-class ModeratorProfile(models.Model):
+class TestModeratorProfile(UserRole):
stars = models.IntegerField()
56 userroles/tests.py
View
@@ -5,16 +5,16 @@
from django.contrib.auth.models import User
from milkman.dairy import milkman
from userroles.models import set_user_role, UserRole
-from userroles.testapp.models import ModeratorProfile
+from userroles.testapp.models import TestModeratorProfile
from userroles.utils import SettingsTestCase
from userroles import Roles
# Test setup
roles_config = (
- ('manager', ''),
- ('moderator', 'userroles.testapp.models.ModeratorProfile'),
- ('client', ''),
+ 'manager',
+ 'moderator',
+ 'client',
)
installed_apps_config = list(settings.INSTALLED_APPS)
@@ -31,11 +31,11 @@ def setUp(self):
ROOT_URLCONF='userroles.testapp.urls',
USER_ROLES=roles_config
)
- self.restore_roles = UserRole.valid_roles
- UserRole.valid_roles = roles
+ self.restore_roles = UserRole._valid_roles
+ UserRole._valid_roles = roles
def tearDown(self):
- UserRole.valid_roles = self.restore_roles
+ UserRole._valid_roles = self.restore_roles
class DummyClass(object):
@@ -113,30 +113,30 @@ def test_set_role_with_profile(self):
"""
Set a role that takes a profile.
"""
- set_user_role(self.user, roles.moderator, ModeratorProfile(stars=5))
+ set_user_role(self.user, roles.moderator, TestModeratorProfile(stars=5))
self.assertTrue(self.user.role.is_moderator)
self.assertEquals(self.user.role.profile.stars, 5)
- def test_set_role_without_profile_incorrectly(self):
- """
- Attempt to set a profile on a role that does not take a profile.
- """
- args = (self.user, roles.client, ModeratorProfile())
- self.assertRaises(ValueError, set_user_role, *args)
-
- def test_set_role_with_profile_incorrectly(self):
- """
- Attempt to set a role that uses profiles, without setting a profile.
- """
- args = (self.user, roles.moderator, )
- self.assertRaises(ValueError, set_user_role, *args)
-
- def test_set_role_with_profile_using_wrong_profile(self):
- """
- Attempt to set a role that uses profiles, without setting a profile.
- """
- args = (self.user, roles.moderator, DummyClass())
- self.assertRaises(ValueError, set_user_role, *args)
+ # def test_set_role_without_profile_incorrectly(self):
+ # """
+ # Attempt to set a profile on a role that does not take a profile.
+ # """
+ # args = (self.user, roles.client, ModeratorProfile())
+ # self.assertRaises(ValueError, set_user_role, *args)
+
+ # def test_set_role_with_profile_incorrectly(self):
+ # """
+ # Attempt to set a role that uses profiles, without setting a profile.
+ # """
+ # args = (self.user, roles.moderator, )
+ # self.assertRaises(ValueError, set_user_role, *args)
+
+ # def test_set_role_with_profile_using_wrong_profile(self):
+ # """
+ # Attempt to set a role that uses profiles, without setting a profile.
+ # """
+ # args = (self.user, roles.moderator, DummyClass())
+ # self.assertRaises(ValueError, set_user_role, *args)
# Tests for user role view decorators
Please sign in to comment.
Something went wrong with that request. Please try again.