def filter_queryset(self, request, queryset, view):
     user = request.user
     model_cls = queryset.model
     kwargs = {
         'app_label': model_cls._meta.app_label,
         'model_name': get_model_name(model_cls)
     }
     permission = self.perm_format % kwargs
     return guardian.shortcuts.get_objects_for_user(user, permission, queryset)
 def get_required_permissions(self, method, model_cls):
     """
     Given a model and an HTTP method, return the list of permission
     codes that the user is required to have.
     """
     kwargs = {
         'app_label': model_cls._meta.app_label,
         'model_name': get_model_name(model_cls)
     }
     return [perm % kwargs for perm in self.perms_map[method]]
    def setUp(self):
        from guardian.shortcuts import assign_perm

        # create users
        create = User.objects.create_user
        users = {
            'fullaccess': create('fullaccess', '*****@*****.**', 'password'),
            'readonly': create('readonly', '*****@*****.**', 'password'),
            'writeonly': create('writeonly', '*****@*****.**', 'password'),
            'deleteonly': create('deleteonly', '*****@*****.**', 'password'),
        }

        # give everyone model level permissions, as we are not testing those
        everyone = Group.objects.create(name='everyone')
        model_name = get_model_name(BasicPermModel)
        app_label = BasicPermModel._meta.app_label
        f = '{0}_{1}'.format
        perms = {
            'view': f('view', model_name),
            'change': f('change', model_name),
            'delete': f('delete', model_name)
        }
        for perm in perms.values():
            perm = '{0}.{1}'.format(app_label, perm)
            assign_perm(perm, everyone)
        everyone.user_set.add(*users.values())

        # appropriate object level permissions
        readers = Group.objects.create(name='readers')
        writers = Group.objects.create(name='writers')
        deleters = Group.objects.create(name='deleters')

        model = BasicPermModel.objects.create(text='foo')

        assign_perm(perms['view'], readers, model)
        assign_perm(perms['change'], writers, model)
        assign_perm(perms['delete'], deleters, model)

        readers.user_set.add(users['fullaccess'], users['readonly'])
        writers.user_set.add(users['fullaccess'], users['writeonly'])
        deleters.user_set.add(users['fullaccess'], users['deleteonly'])

        self.credentials = {}
        for user in users.values():
            self.credentials[user.username] = basic_auth_header(user.username, 'password')
 def get_required_object_permissions(self, method, model_cls):
     kwargs = {
         'app_label': model_cls._meta.app_label,
         'model_name': get_model_name(model_cls)
     }
     return [perm % kwargs for perm in self.perms_map[method]]