Giter VIP home page Giter VIP logo

django-role-permissions's Introduction

django-role-permissions

Build Status Coverage Status Current version at PyPI Supported Python Versions

django-role-permissions is a django app for role based permissions. It's built on top of django contrib.auth user Group and Permission functionalities and it does not add any other models to your project.

django-role-permissions supports Django versions from 1.5 until the latest.

Version 2.x now supports multiple roles!

Documentation

Documentation is available at:

http://django-role-permissions.readthedocs.org/

If you are still using the 1.x version the old documentation is at:

http://django-role-permissions.readthedocs.io/en/1.x/

Running tests

This packages uses tox to run tests on multiple evironments, please make sure they are passing before submitting a pull request. To run tests, install tox and run it in the command line from this project's folder:

$ tox

Maintainers

How to Release:

Pre release:

  • Include the changes in CHANGELOG
  • Update the version in rolepermissions/__init__.py
  • Update the classifiers in setup.py

Release:

Post release:

Help

If you have any questions or need help, please send an email to: [email protected]

Commercial Support

alt text

This project is maintained by Vinta Software and is used in products of Vinta's clients. We are always looking for exciting work, so if you need any commercial support, feel free to get in touch: [email protected]

Copyright (c) 2019 Vinta Serviços e Soluções Tecnológicas Ltda. MIT License

django-role-permissions's People

Contributors

aarcro avatar amandasavluchinske avatar andersonresende avatar benvdh avatar dennys-bd avatar filipeximenes avatar finnertysea avatar fjsj avatar huogerac avatar iurisilvio avatar jamespenick avatar kavdev avatar magnunleno avatar myonov avatar philippeluickx avatar powderflask avatar reduxionist avatar rsarai avatar sdee avatar snmishra avatar soloincc avatar valberg avatar victorgutemberg avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-role-permissions's Issues

Implementation of instance specific roles?

Consider the case, where a doctor is assigned patients, and is from a specific hospital
e.g. Hospital_A->Doctor_A->Patient_A
, Hospital_A->Doctor_B->Patient_B
, and Hospital_C->Doctor_C->Patient_C

Doctors have permissions such that they are able to read all records from their assigned hospital, and update the medical record of their assigned patients

In this case, an instance of a doctor should be able to update ONLY the medical record of the patients he/she has been assigned to, i.e. Doctor_B is not allowed to access the records of other patients, e.g. Patient_A, but he can view the records of his assigned patient, Patient_B.

Furthermore, the queryset of patient records should be filtered based on the Hospital that the Doctors belong to. E.g. Doctors A and B can view records originating from Hospital_A, but not from Hospital_C

Is it then possible to implement this level of access control via the concept of Roles through this package?

Thanks

Changelog for 2.2.0

Hi,

I would like to ask if there is any changelog detailing the changes made between versions released, especially between 2.2.0 and 2.1.0?
Thanks

HasObjectPermissionMixin

from django.contrib.auth.views import redirect_to_login
from django.core.exceptions import PermissionDenied
from django.conf import settings

from rolepermissions.verifications import has_object_permission


class HasObjectPermissionMixin(object):
    checker_name = ''

    def dispatch(self, request, *args, **kwargs):
        user = request.user
        if user.is_authenticated():
            self.object = self.get_object()
            if has_object_permission(self.checker_name, request.user, self.object):
                return super().dispatch(request, *args, **kwargs)

        if hasattr(settings, 'ROLEPERMISSIONS_REDIRECT_TO_LOGIN'):
            return redirect_to_login(request.get_full_path())

        raise PermissionDenied

Support multiple roles

From what I've seen in the code, it seems that though the app could support multiple roles per user, it supports only one.

For example assign_role_to_user will delete all of the user's previous roles:
https://github.com/vintasoftware/django-role-permissions/blob/master/rolepermissions/roles.py#L50

And get_user_role explicitely return only the first role if the user has multiple roles:

Is there a reason for not supporting multiple roles? Before diving into the code, I would like to have an idea on how difficult could implementing such a feature be ? Would a PR working towards implementing this feature be considered?

Thanks.

Cant access get the functions to return roles in my views or template

Hi, Great Package, I have a small issue or I am missing something, in any I need help, now I can assign roles, but I can only successfully return when I am using the shell, it completely fails on when trying vies or templates.

Its probably a very easy problem to solve

thanks in advance.
A

SystemError exception when an AppConfig dotted path specified in INSTALLED_APPS

In older Django versions, in settings.py in INSTALLED_APPS one used to specify the name of a module. In recent Django versions (I think 1.7+) you can specify a dotted path to an AppConfig instance and I even think that's the default, since it's listed as the first option to include apps: https://docs.djangoproject.com/en/1.9/ref/applications/#configuring-applications or to quote directly "To configure an application, subclass AppConfig and put the dotted path to that subclass in INSTALLED_APPS.". Specifying an app in this way breaks django-role-permissions. Here's a stack trace:

Traceback (most recent call last):
  File "./manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/home/vagrant/virtualenvs/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
    utility.execute()
  File "/home/vagrant/virtualenvs/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 327, in execute
    django.setup()
  File "/home/vagrant/virtualenvs/venv/lib/python3.4/site-packages/django/__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/home/vagrant/virtualenvs/venv/lib/python3.4/site-packages/django/apps/registry.py", line 115, in populate
    app_config.ready()
  File "/home/vagrant/virtualenvs/venv/lib/python3.4/site-packages/rolepermissions/apps.py", line 12, in ready
    load_roles_and_permissions()
  File "/home/vagrant/virtualenvs/venv/lib/python3.4/site-packages/rolepermissions/loader.py", line 14, in load_roles_and_permissions
    import_module('.permissions', app_name)
  File "/home/vagrant/virtualenvs/venv/lib/python3.4/importlib/__init__.py", line 109, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 2249, in _gcd_import
  File "<frozen importlib._bootstrap>", line 2199, in _sanity_check
SystemError: Parent module 'lists.apps.ListsConfig' not loaded, cannot perform relative import

It works when INSTALLED_APPS contains lists, but not when it contains lists.apps.ListsConfig. This breaks only django-role-permissions - if I remove django-role-permissions from INSTALLED_APPS, the rest works perfectly fine, so it's not a project error.

The workaround I've found for now is to make this AppConfig the default one by adding default_app_config = 'lists.apps.ListsConfig' to lists/__init__.py and the listing only the module name (lists) in INSTALLED_APPS, but ideally this should be fixed in django-role-permissions.

Django-role-permission duplicate queries

Hello,

Am experiencing duplicate queries for function has_permission

I have a decorator as follows:

def canAccessDashboard(func):
    def func_wrapper(*args):
        user = cache.get('UserObj_' + str(args[0].user.id))
        if user is None:
            user = User.objects.get(id=args[0].user.id)
            cache.set('UserObj_' + str(args[0].user.id), user, 300)
        if has_permission(user, "access_dasboard"):
            if not has_permission(user, "add_merchant_address"):
                return render(args[0], 'dashboard/specify_address.html')
            return func(*args)
        return redirect(settings.VERIFY_REGISTRATION_URL)
    return func_wrapper

Which is called on my django view as decorator:

@canAccessDashboard
def index(request):
    """ Merchant settings main page"""
    try:
        return render(request, 'dashboard/merchantsettings.html')
    except Exception as e:
        return HttpResponse('NOK', status=500)

The issue is that am experiencing duplicate queries for each permission in my available_permission:

available_permissions = {
        'access_dasboard': False,
        'add_merchant_address': False,
        'immediate_cashout': False,
        'update_merchant_address': False
    }

SELECT ••• FROM "auth_permission" INNER JOIN "auth_user_user_permissions" ON ("auth_permission"."id" = "auth_user_user_permissions"."permission_id") INNER JOIN "django_content_type" ON ("auth_permission"."content_type_id" = "django_content_type"."id") WHERE "auth_user_user_permissions"."user_id" = 16 ORDER BY "django_content_type"."app_label" ASC, "django_content_type"."model" ASC, "auth_permission"."codename" ASC
Duplicated 8 times.

SELECT ••• FROM "auth_permission" WHERE ("auth_permission"."content_type_id" = 4 AND "auth_permission"."codename" = 'add_merchant_address')
Duplicated 8 times

SELECT ••• FROM "auth_permission" WHERE ("auth_permission"."content_type_id" = 4 AND "auth_permission"."codename" = 'immediate_cashout')
Duplicated 8 times.

SELECT ••• FROM "auth_permission" WHERE ("auth_permission"."content_type_id" = 4 AND "auth_permission"."codename" = 'access_dasboard') Duplicated 8 times

Can you please fix it out?

Thank you in advance.

Exclusive use of Groups

I think it's a mistake to assume each user is in a single group related to a single role. In 6852439 you removed the UserRole model but I'd like to see it restored.

I was expecting that 'role' was entirely separate from groups. I intend to have my Users in groups by team, and given a role 'team_member' they would be granted the permission 'change_team_documents'. I could then use the object level permissions checks to ensure that user.has_perm('change_team_documents') and doc.team in user.groups.all()

At a minimum I'd hope the use of groups could be reworked to drop the single group assumption. Possibly filter for groups that match role names, and delete only "role groups".

I'm not even sure why assign_role_to_user() removes previous rolls. Further, available_permissions doesn't actually limit the permissions that can be applied to a user, default False permissions have no effect at all. It might make more sense to just have default_permissions as a list, thus users granted multiple rows will just have the permissions from each roll.

Sorry for the novel here. If you're interested I'm happy to split the issues up and work on solutions.

available_perm_status: 'UserPermission' is not defined

Hi,
I am trying to use it with Django1.8 but I keep getting 'UserPermission' is not defined. Following is what I did and yes I have included it in settings.py and migrated:

from college.roles import Student
student = User.objects.get(username='jassi')
Student.assign_role_to_user(student)
from rolepermissions.shortcuts import available_perm_status
permis = available_perm_status(student)

error

Traceback (most recent call last):
 File "<console>", line 1, in <module>
 File "/home/jassi/.venvs/college/local/lib/python2.7/site-packages/rolepermissions/shortcuts.py",   line 33, in available_perm_status
permissions = UserPermission.objects.filter(user=user)
NameError: global name 'UserPermission' is not defined

Add an admin widget to manage Roles

I'm not sure this is even possible, but it would be pretty cool to have some sort of admin UI for adding and removing roles and permissions

Revoking the role

I find revoke permission.
But, I want to revoke the role instead.

Add a management command to sync roles/permissions

If the available_permissions dict on a Role changes, I'm pretty sure it won't be in sync with the groups/permissions set in the database unless the roles get re-assigned.

We don't plan on explicitly removing permissions in our project, so our solution is a management command that checks which roles each user has, clears them, and then reassigns them.

Not sure how you want to go about this, but I can make a pull request when our solution is ready if you want.

model User is not registered

  File "/home/x/y/.venvs/z/lib/python3.6/site-packages/rolepermissions/admin.py", line 40, in <module>
    admin.site.unregister(UserModel)
  File "/home/x/y/.venvs/z/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 136, in unregister
    raise NotRegistered('The model %s is not registered' % model.__name__)
django.contrib.admin.sites.NotRegistered: The model User is not registered

I have 2 roles defined and one superuser that has neither defined (fresh deployment of site), but for which I want to define a role through admin interface.

edit: I am using a custom user model.

Error installing with pip

Hi,

I'm getting this error when trying to install this package with pip:

C:\Python34>cd scripts

C:\Python34\Scripts>pip install django-role-permissions
Downloading/unpacking django-role-permissions
Downloading django-role-permissions-0.4.2.tar.gz
Running setup.py (path:C:\Users\Manuel\AppData\Local\Temp\pip_build_Manuel\dja
ngo-role-permissions\setup.py) egg_info for package django-role-permissions
Traceback (most recent call last):
File "", line 17, in
File "C:\Users\Manuel\AppData\Local\Temp\pip_build_Manuel\django-role-perm
issions\setup.py", line 59
print "You probably want to also tag the version now:"
^
SyntaxError: Missing parentheses in call to 'print'
Complete output from command python setup.py egg_info:
Traceback (most recent call last):

File "", line 17, in

File "C:\Users\Manuel\AppData\Local\Temp\pip_build_Manuel\django-role-permissi
ons\setup.py", line 59

print "You probably want to also tag the version now:"

                                                     ^

SyntaxError: Missing parentheses in call to 'print'


Cleaning up...
Command python setup.py egg_info failed with error code 1 in C:\Users\Manuel\App
Data\Local\Temp\pip_build_Manuel\django-role-permissions
Storing debug log for failure in C:\Users\Manuel\pip\pip.log

Why can this be happening? maybe I need something else? sorry if it's my fault I'm new to python

Few notes regading package.

Hi!

load_roles_and_permissions()

Why do you require to run load_roles_and_permissions() in urls.py? By doing that you cannot access your roles globally, since urls.py is not always processed (imagine celery tasks). I've tried to move this call into rolespermissions/__init__.py and had no problems - all tests passes and I'm no longer obligated to include this call into urls.py and I'm sure RolesManager.get_roles() always returns my roles because they were parsed on module import time.

Running tests

I was not able to run particular tests because they cannot be found. I've fixed it by adding following lines into tests/__init__.py:

from .test_decorators import *
from .test_mixins import *
from .test_permissions import *
from .test_roles import *
from .test_shortcuts import *
from .test_template_tags import *
from .test_verifications import *

CBV Tests are probably out of date

CBV tests were DetailView is used fails with Exception saying: Template mixin requires template_name or get_template_names() to be defined in concrete class. I've fixed this by adding custom response class and overriding render_to_response method like this:

OLD

class HasRoleDetailView(DetailView):

    @method_decorator(has_role_decorator('role1'))
    def dispatch(self, request, *args, **kwargs):
        return super(HasRoleDetailView, self).dispatch(request, *args, **kwargs)

    def get_object(self, queryset=None):
        return True

NEW

# head of a file...
from django.http.response import HttpResponse

class HasRoleDetailView(DetailView):

    @method_decorator(has_role_decorator('role1'))
    def dispatch(self, request, *args, **kwargs):
        return super(HasRoleDetailView, self).dispatch(request, *args, **kwargs)

    def get_object(self, queryset=None):
        return True

    def render_to_response(self, context, **response_kwargs):
        return HttpResponse("Test")

How do I change the permission for a role rather than a user?

I have created two roles like this

class LevelOne(AbstractUserRole):
   available_permissions = {

       'view_details': True,
       'edit_details': True,
       'drop_tables': False,
       'edit_profile': False,
   }
class LevelTwo(AbstractUserRole):
   available_permissions = {

       'view_details': True,
       'edit_details': True,
       'drop_tables': True,
       'edit_profile': True,
   }

Now I want to be able to change the permission for either of the roles at will.
Suppose I want to set the permission edit_profile to True for LevelOne role.
How do I achieve that ?

assign_role helper function

def remove_role(user):
    old_groups = user.groups.filter(name__in=registered_roles.keys())
    for old_group in old_groups:  # Normally there is only one, but remove all other role groups
        role = RolesManager.retrieve_role(old_group.name)
        permissions_to_remove = Permission.objects.filter(codename__in=role.permission_names_list()).all()
        user.user_permissions.remove(*permissions_to_remove)
    user.groups.remove(*old_groups)


def assign_role(user, role):
    role_cls = retrieve_role(role)

    remove_role(user)

    if role_cls:
        role_cls.assign_role_to_user(user)
        return role_cls

duplicate key

Hello,

I'm using a custom model inherit from AbstractBaseUser and PermissionMixin, which use phone number as primary key. when I trying to use the your module, like:

CustomRole.assign_role_to_user(custom_user) , I got errors:
File "/usr/local/lib/python2.7/dist-packages/rolepermissions/roles.py", line 68, in assign_role_to_user
permissions_to_add = cls.get_default_true_permissions()
File "/usr/local/lib/python2.7/dist-packages/rolepermissions/roles.py", line 83, in get_default_true_permissions
return cls.get_or_create_permissions(permission_names)
File "/usr/local/lib/python2.7/dist-packages/rolepermissions/roles.py", line 96, in get_or_create_permissions
content_type=user_ct, codename=permission_name)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 127, in manager_method
return getattr(self.get_queryset(), name)(_args, *_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 407, in get_or_create
return self._create_object_from_params(lookup, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 447, in _create_object_from_params
six.reraise(_exc_info)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 439, in _create_object_from_params
obj = self.create(__params)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 348, in create
obj.save(force_insert=True, using=self.db)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 710, in save
force_update=force_update, update_fields=update_fields)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 738, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 822, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 861, in _do_insert
using=using, raw=raw)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 127, in manager_method
return getattr(self.get_queryset(), name)(_args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 920, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 974, in execute_sql
cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 97, in exit
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
IntegrityError: duplicate key value violates unique constraint "auth_permission_pkey"
DETAIL: Key (id)=(1) already exists.

from my prosgresql log:
2015-09-03 17:32:26 CST [12080-1] aaa@bbb ERROR: duplicate key value violates unique constraint "auth_permission_pkey"
2015-09-03 17:32:26 CST [12080-2] aaa@bbb DETAIL: Key (id)=(1) already exists.
2015-09-03 17:32:26 CST [12080-3] aaa@bbb STATEMENT: INSERT INTO "auth_permission" ("name", "content_type_id", "codename") VALUES ('', 7, 'create_booking') RETURNING "auth_permission"."id"

Any idea about what's the problem?

cheers,

Error running the tests

Hi,

When I was running the tests: python setup.py test

I got the following error, am I doing something wrong?

.../django-role-permissions/.eggs/Sphinx-1.4.1-py2.7.egg
Traceback (most recent call last):
  File "setup.py", line 90, in <module>
    tests_require=test_requirements
  File "/usr/lib/python2.7/distutils/core.py", line 151, in setup
    dist.run_commands()
  File "/usr/lib/python2.7/distutils/dist.py", line 953, in run_commands
    self.run_command(cmd)
  File "/usr/lib/python2.7/distutils/dist.py", line 972, in run_command
    cmd_obj.run()
  File ".../workspacepy/dj19/local/lib/python2.7/site-packages/setuptools/command/test.py", line 152, in run
    self.distribution.fetch_build_eggs(self.distribution.tests_require)
  File ".../workspacepy/dj19/local/lib/python2.7/site-packages/setuptools/dist.py", line 313, in fetch_build_eggs
    replace_conflicting=True,
  File ".../workspacepy/dj19/local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 825, in resolve
    dist = best[req.key] = env.best_match(req, ws, installer)
  File ".../workspacepy/dj19/local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 1063, in best_match
    dist = working_set.find(req)
  File ".../workspacepy/dj19/local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 700, in find
    raise VersionConflict(dist, req)
pkg_resources.VersionConflict: (six 1.9.0 (.../workspacepy/dj19/lib/python2.7/site-packages), Requirement.parse('six==1.3.0'))

Cheers

HasRoleMixin could redirect to login page

I've just started using the django-role-permissions and loved it.

I'd like to block my Views (CBV) for specific Roles:

class MyListView(HasRoleMixin, ListView):
        allowed_roles = 'Admin'
        ...

It's working in terms of permissions, however, I'd like to be redirect to the login page when I have no permission or not logged in rather than get a 403 Forbidden error.

My solution today is using role-permissions + django-braces where I do something like bellow rather than the HasRoleMixin:

class MyListView(LoginRequiredMixin, UserPassesTestMixin, ListView):

    def test_func(self, user):
        return has_role(user, [Admin, ])

This way, when the user has no permission, it goes to the login page and the workflow works very well.

Is there any settings that I could do this behavior without using braces? in other others, intercept the 403 error and do something else?

I'd be happy if you guys give me some directions that lead me to do some pull request and contribute to this amazing app.

Cheers

Support for Django 1.11

Django 1.11rc1 is out now and the feature-set is frozen. Can you please add support for the new version to django-role-permissions as we want to start testing with the new release?

ValueError: invalid version number '1.11rc1'

[Enhancement] Add name value to Permissions object creation in AbstractUserRole.

The following line:

@classmethod
def get_or_create_permissions(cls, permission_names):

  ...
  permission, created = Permission.objects.get_or_create(content_type=user_ct,
                                                         codename=permission_name)
  ...

Ends up with not very descriptive permissions names e.g. auth | user |. The lack of name leaves the last value of the string representation of the object blank.

It would be a nice enhancement to have the ability to "Capital Case And Space" the permission_name assigned to the codename value in the Permissions object instance.

This would in turn allow for the following example permission description: auth | user | Can Edit Role

I don't have time at the moment to submit a PR that would facilitate this transformation. I am also unsure how to make this change backwards compatible with the Permissions.object.get_or_create method.

Can coexist with django-guardian and django-groups-manager?

Hi,

I need to implement the permission with a general role for a specific group, like staff group that handle the group.

I explain the example:

from football.models import TeamBudget
from groups_manager.models import Group, Member

fc_internazionale = Group.objects.create(name='F.C. Internazionale Milan')
staff = Group.objects.create(name='Staff', parent=fc_internazionale)
players = Group.objects.create(name='Players', parent=fc_internazionale)
thohir = Member.objects.create(first_name='Eric', last_name='Thohir')
staff.add_member(thohir)
palacio = Member.objects.create(first_name='Rodrigo', last_name='Palacio')
players.add_member(palacio)
small_budget = TeamBudget.objects.create(euros='1000')
thohir.assign_object(staff, small_budget)
thohir.has_perm('change_teambudget', small_budget)  # True
palacio.has_perm('change_teambudget', small_budget)  # False
# or via group
mid_budget = TeamBudget.objects.create(euros='3000')
staff.assign_object(mid_budget)
thohir.has_perm('change_teambudget', mid_budget)  # True
palacio.has_perm('change_teambudget', mid_budget)  # False

The staff member can handle the group and group descendent
Is possible to implement?

Using package with Factory Boy

Hi. I'm having issues with creating a factory for my roles. Any ideas how to fix that? Thanks!

roles.py

from rolepermissions.roles import AbstractUserRole

from applications.models import Application


class Evaluator(AbstractUserRole):
    available_permissions = dict(map(lambda x: (x[0], True), Application._meta.permissions))

factories.py

import factory

from django.conf import settings

from rolepermissions.shortcuts import assign_role

from project.roles import Operator
from universities.factories import UniversityFactory


class EvaluatorFactory(factory.django.DjangoModelFactory):
    email = factory.Sequence(lambda n: 'evaluator%[email protected]' % n)
    password = factory.PostGenerationMethodCall('set_password', settings.TEST_LOGIN_PASSWORD)
    first_name = factory.Faker('first_name')
    last_name = factory.Faker('last_name')
    university = factory.SubFactory(UniversityFactory)

    role = factory.PostGeneration(lambda obj, create, extracted, **kwargs: assign_role(obj, Evaluator))

    class Meta:
        model = 'users.User'
        django_get_or_create = ('email',)

My test are throwing errors like:

======================================================================
ERROR: test_access_denied_anonymous (users.tests.test_views.UserToggleStatusTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/mike/Projects/project/users/tests/test_views.py", line 118, in setUp
    self.evaluator = EvaluatorFactory()
  File "/Users/mike/.pyenv/versions/project/lib/python3.5/site-packages/factory/base.py", line 67, in __call__
    return cls.create(**kwargs)
  File "/Users/mike/.pyenv/versions/project/lib/python3.5/site-packages/factory/base.py", line 594, in create
    return cls._generate(True, attrs)
  File "/Users/mike/.pyenv/versions/project/lib/python3.5/site-packages/factory/base.py", line 525, in _generate
    results[name] = decl.call(obj, create, extraction_context)
  File "/Users/mike/.pyenv/versions/project/lib/python3.5/site-packages/factory/declarations.py", line 562, in call
    extraction_context.value, **extraction_context.extra)
  File "/Users/mike/Projects/project/users/factories.py", line 52, in <lambda>
    role = factory.PostGeneration(lambda obj, create, extracted, **kwargs: assign_role(obj, Evaluator))
  File "/Users/mike/.pyenv/versions/project/lib/python3.5/site-packages/rolepermissions/shortcuts.py", line 31, in assign_role
    raise RoleDoesNotExist
rolepermissions.exceptions.RoleDoesNotExist

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.