django.contrib.auth.models.Group.objects.filter - python examples

Here are the examples of the python api django.contrib.auth.models.Group.objects.filter taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

18 Examples 7

3 View Complete Implementation : forms.py
Copyright BSD 2-Clause "Simplified" License
Author : awemulya
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request')
        super(SetProjectRoleForm, self).__init__(*args, **kwargs)
        self.fields['group'].empty_label = None
        role = kwargs.get('instance')
        if role is not None:
            old_admins = role.project.get_staffs_both_role
            old_admins.append(settings.ANONYMOUS_USER_ID)
            if hasattr(self.request, "organization"):
                if self.request.organization:
                    users = User.objects.filter(is_active=True, user_profile__organization=self.request.organization)\
                        .exclude(id__in=old_admins)
                else:
                    users = User.objects.filter(is_active=True).exclude(id__in=old_admins)
            else:
                users = User.objects.filter(is_active=True).exclude(id__in=old_admins)
            self.fields['user'].queryset = users
        self.fields['group'].queryset = Group.objects.filter(
            name__in=['Project Manager'])

3 View Complete Implementation : users_util.py
Copyright Apache License 2.0
Author : elvinzeng
def hr_group():
    hr_group_list = Group.objects.filter(name="hr")
    if len(hr_group_list) > 0:
        return hr_group_list[0]
    else:
        raise Exception("User group 'hr' not found.")

3 View Complete Implementation : users_util.py
Copyright Apache License 2.0
Author : elvinzeng
def staff_group():
    staff_group_list = Group.objects.filter(name="staff")
    if len(staff_group_list) > 0:
        return staff_group_list[0]
    else:
        raise Exception("User group 'staff' not found.")

3 View Complete Implementation : permissions.py
Copyright GNU General Public License v2.0
Author : kiwitcms
def initiate_user_with_default_setups(user):
    """
    Add default groups, permissions, status to a newly
    created user.
    """
    # create default permissions if not already set
    astign_default_group_permissions()

    default_groups = Group.objects.filter(name__in=settings.DEFAULT_GROUPS)
    for grp in default_groups:
        user.groups.add(grp)

    user.is_staff = True  # so they can add Products, Builds, etc via the ADMIN menu
    user.save()

3 View Complete Implementation : apps.py
Copyright Mozilla Public License 2.0
Author : mozilla-services
def attach_token_permissions(sender, **kwargs):
    from django.contrib.auth.models import Group, Permission

    # There are certain groups that make no sense if they don't also
    # have the 'manage_tokens' permission.
    names = ("Uploaders", "Upload Auditors")
    for group in Group.objects.filter(name__in=names):
        group.permissions.add(Permission.objects.get(codename="manage_tokens"))

3 View Complete Implementation : myfilter.py
Copyright GNU General Public License v3.0
Author : qitan
@register.filter(name='user_groups')
def all_user_groups(pk):
    '''
    用户所属组
    '''

    try:
        user_group = [i.name for i in Group.objects.filter(user=pk)]
        return user_group
    except:
        return ''

0 View Complete Implementation : survey_view.py
Copyright Apache License 2.0
Author : bcgov
    def dispatch(self, request, *args, **kwargs):

        # ensure that there is a user whose authentication can be validated
        if not hasattr(request, 'user'):
            self.request = request
            return self.handle_no_permission()

        # LoginRequired
        if not request.user.is_authenticated:
            self.request = request
            return self.handle_no_permission()

        user_groups = Group.objects.filter(user=request.user)
        admin_group = Group.objects.get(name='admin')

        if admin_group not in user_groups:
            if self.raise_exception or self.request.user.is_authenticated:
                raise PermissionDenied("Prermission Denied")
            return redirect_to_login(self.request.get_full_path(), self.get_login_url(),
                                     self.get_redirect_field_name())

        request_handler = self

        _method = request.POST.get('_method')

        if _method is None:
            _method = request.method

        if _method is not None:
            if _method.upper() in SurveyView.http_methods:
                handler_method = get_handler_method(
                    request_handler, _method.upper())

                if handler_method:
                    return handler_method(request, *args, **kwargs)
            else:
                methods = [method for method in http_methods if get_handler_method(
                    request_handler, _method)]
                if len(methods) > 0:
                    return HttpResponseNotAllowed(methods)
                else:
                    return HttpResponseServerError("Invalid method")

0 View Complete Implementation : user_initialization.py
Copyright GNU General Public License v3.0
Author : CalthorpeAnalytics
def update_or_create_group(name, config_ensaty=None, superiors=None):
    """
        Create a group and GroupHierarchy instance. Group is the Django Group model, whereas
        GroupHierarchy is a Footprint model that astociates a Group to superior Groups and to
        a ConfigEnsaty
    :param name: Required name of the group
    :param config_ensaty: Optional. Required for config_ensaty scoped groups. Always null
    for the default groups (e.g. Admin, Directory)
    :param superiors: Optional superiors to the group. All groups should have superiors except
    for the Admin group
    :return:
    """
    group = get_single_value_or_create(
        Group.objects.filter(name=name),
        lambda: Group.objects.get_or_create(name=name)[0])
    # Make sure the group has full permission to every model
    # We limit permission on individual instances
    new_permissions = set(Permission.objects.all())-set(group.permissions.all())
    group.permissions.add(*new_permissions)
    # Track the superiors in our special clast
    try:
        superior_groups = map(lambda superior: Group.objects.get(name=superior), superiors or [])
    except:
        raise Exception("Expected groups %s to exist but only these exist: %s" %\
              (superiors, Group.objects.values_list('name')))
    group_hierarchy, created, updated = GroupHierarchy.objects.update_or_create(
        group=group,
        defaults=dict(config_ensaty=config_ensaty)
    )
    if not created:
        group_hierarchy.superiors.clear()
    for superior_group in superior_groups:
        group_hierarchy.superiors.add(superior_group)
    return group

0 View Complete Implementation : user_publishing.py
Copyright GNU General Public License v3.0
Author : CalthorpeAnalytics
def on_config_ensaty_post_save_group(sender, **kwargs):
    """
        Syncs the user, groups, and permissions for the ConfigEnsaty
        Some ConfigEnsaty clastes create their own Groups and default
        Users. This makes it easy to give a client-specific user permission
        to certain ConfigEnsaty by joining the latter's group
    :param sender:
    :param kwargs:
    :return:
    """

    config_ensaty = InstanceBundle.extract_single_instance(**kwargs)
    if config_ensaty._no_post_save_publishing:
        return
    user = kwargs.get('user')
    logger.info("Handler: post_save_user for config_ensaty {config_ensaty} and user {username}".format(
        config_ensaty=config_ensaty.name,
        username=user.username if user else 'undefined'))

    if kwargs.get('created') and not config_ensaty.creator:
        # Set the ConfigEnsaty.creator to the default admin group user if it wasn't set by the API
        config_ensaty.creator = User.objects.get(username=UserGroupKey.SUPERADMIN)
        config_ensaty._no_post_save_publishing = True
        config_ensaty.save()
        config_ensaty._no_post_save_publishing = False

    # First update_or_create any default groups. This usually just applies to global_config
    from footprint.client.configuration.fixture import UserFixture
    from footprint.client.configuration.utils import resolve_fixture
    user_fixture = resolve_fixture("user", "user", UserFixture, config_ensaty.schema(),
                                   config_ensaty=config_ensaty)
    for group_fixture in user_fixture.groups():
        group = update_or_create_group(**group_fixture)
        logger.info("User Publishing. For ConfigEnsaty %s synced global UserGroup: %s" %
                    (config_ensaty.name, group.name))

    # Sync permissions for the ConfigEnsaty
    # Resolve the default ConfigEnsaty permissions for this config_ensaty
    # Update or Create the ConfigEnsaty Group(s) for this ConfigEnsaty
    config_ensaty_groups = _update_or_create_config_ensaty_groups(config_ensaty)
    # Get the mapping of groups to permission types for the config_ensaty's most relevant fixture
    # These group keys are generally all global groups.
    from footprint.client.configuration.fixture import ConfigEnsatiesFixture
    config_ensaties_fixture = resolve_fixture("config_ensaty", "config_ensaties", ConfigEnsatiesFixture, config_ensaty.schema())
    permission_lookup = config_ensaties_fixture.default_config_ensaty_permissions()
    # Set the permissions for the config_ensaty groups. This will also set all superior group permissions
    # to the same permissions or greater is they match something in the permission_lookup
    config_ensaty_group_permissions = sync_config_ensaty_group_permissions(
        config_ensaty, config_ensaty_groups, permission_lookup, permission_key_clast=ConfigEnsatyPermissionKey, **kwargs)

    # Give the groups read permissions on the ancestor config_ensaties
    # TODO restrict this access further for the UserGroupKey.DEMO group
    groups = Group.objects.filter(name__in=config_ensaty_group_permissions.keys())
    for config_ensaty in config_ensaty.ancestors:
        config_ensaty.astign_permission_to_groups(groups, PermissionKey.VIEW)

    # TODO tell children to add themselves to all ancestors (resync)
    # This will only be needed if the parent ConfigEnsaty group permission configuration changes

    reset_queries()

0 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : CalthorpeAnalytics
@login_required(login_url='/footprint/login')
def users(request):
    users = OrderedDict()
    config_keys = {}

    user_role = get_role_key_for_user(request.user)
    for subclast in ROLE_SUBCLastES_MAP[user_role]:
        for config in subclast.objects.all().order_by('name'):

            if not user_has_permission_for_config_ensaty(request.user, config):
                continue

            if config.key == Keys.GLOBAL_CONFIG_KEY:
                for group in Group.objects.filter(name__in=USER_EDIT_PERMISSIONS_MAP[user_role]):
                    if group.user_set.count():

                        if config.name not in users:
                            users[config.name] = []
                            config_keys[config.name] = config.key

                        for user in group.user_set.all():
                            users[config.name].append({
                                'user': user,
                                'role': get_role_key_for_user(user).capitalize()
                            })

            else:
                for group_hierarchy in config.group_hierarchies.all():
                    if group_hierarchy.group:
                        _role_key = get_role_key_for_group(group_hierarchy.group)

                        if _role_key not in USER_EDIT_PERMISSIONS_MAP[user_role]:
                            continue

                        if group_hierarchy.group.user_set.count():
                            if config.name not in users:
                                users[config.name] = []
                                config_keys[config.name] = config.key

                            for user in group_hierarchy.group.user_set.all():
                                users[config.name].append({
                                    'user': user,
                                    'role': _role_key.capitalize()
                                })

    return render(
        request,
        'footprint/users.html',
        {
            'users': users,
            'config_keys': config_keys,
            'admin_user': request.user,
            'requesting_user_role': user_role
        }
    )