Python django.contrib.auth.models.Group() Examples
The following are 30
code examples of django.contrib.auth.models.Group().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
django.contrib.auth.models
, or try the search function
.
Example #1
Source File: test_multi_model_form_view.py From django-shapeshifter with Apache License 2.0 | 6 votes |
def test_form_validation(request_factory): """Forms should still provide errors""" request = request_factory().post( "/", data={ "userform-first_name": "Katherine", "userform-last_name": "Johnson", "userform-username": "KJohnson", "groupform-name": "Admins", }, ) request = get_session_request(request) with mock.patch.object(Group, "save") as mock_group, mock.patch.object( User, "save" ) as mock_user: Membership.as_view()(request) mock_user.assert_called_once() mock_group.assert_called_once()
Example #2
Source File: shortcuts.py From resolwe with Apache License 2.0 | 6 votes |
def _group_groups(perm_list): """Group permissions by group. Input is list of tuples of length 3, where each tuple is in following format:: (<group_id>, <group_name>, <single_permission>) Permissions are regrouped and returned in such way that there is only one tuple for each group:: (<group_id>, <group_name>, [<first_permission>, <second_permission>,...]) :param list perm_list: list of touples of length 3 :return: list tuples with grouped permissions :rtype: list """ perm_list = sorted(perm_list, key=lambda tup: tup[0]) grouped_perms = [] for key, group in groupby(perm_list, lambda tup: (tup[0], tup[1])): grouped_perms.append((key[0], key[1], [g[2] for g in group])) return grouped_perms
Example #3
Source File: views.py From kobo-predict with BSD 2-Clause "Simplified" License | 6 votes |
def add_supervisor(request, pk): obj = get_object_or_404( Site, pk=int(pk), is_active=True) group = Group.objects.get(name__exact="Site Supervisor") role_obj = UserRole(site=obj, group=group) if request.method == 'POST': form = SetSupervisorForm(data=request.POST, instance=role_obj, request=request) if form.is_valid(): role_obj = form.save(commit=False) user_id = request.POST.get('user') role_obj.user_id = int(user_id) role_obj.save() messages.add_message(request, messages.INFO, 'Site Supervisor Added') return HttpResponseRedirect(reverse("fieldsight:site-dashboard", kwargs={'pk': obj.pk})) else: form = SetSupervisorForm(instance=role_obj, request=request) return render(request, "fieldsight/add_supervisor.html", {'obj':obj,'form':form})
Example #4
Source File: views.py From kobo-predict with BSD 2-Clause "Simplified" License | 6 votes |
def add_proj_manager(request, pk): obj = get_object_or_404( Project, pk=pk, is_active=True) group = Group.objects.get(name__exact="Project Manager") role_obj = UserRole(project=obj, group=group) scenario = 'Assign' if request.method == 'POST': form = SetProjectManagerForm(data=request.POST, instance=role_obj, request=request) if form.is_valid(): role_obj = form.save(commit=False) user_id = request.POST.get('user') role_obj.user_id = int(user_id) role_obj.save() messages.add_message(request, messages.INFO, 'Project Manager Added') return HttpResponseRedirect(reverse("fieldsight:project-dashboard", kwargs={'pk': obj.pk})) else: form = SetProjectManagerForm(instance=role_obj, request=request) return render(request, "fieldsight/add_project_manager.html", {'obj':obj,'form':form, 'scenario':scenario})
Example #5
Source File: config.py From django-river with BSD 3-Clause "New" or "Revised" License | 6 votes |
def settings(self): if self.cached_settings: return self.cached_settings else: from django.conf import settings allowed_configurations = { 'CONTENT_TYPE_CLASS': ContentType, 'USER_CLASS': settings.AUTH_USER_MODEL, 'PERMISSION_CLASS': Permission, 'GROUP_CLASS': Group, 'INJECT_MODEL_ADMIN': False } river_settings = {} for key, default in allowed_configurations.items(): river_settings[key] = getattr(settings, self.get_with_prefix(key), default) river_settings['IS_MSSQL'] = connection.vendor == 'microsoft' self.cached_settings = river_settings return self.cached_settings
Example #6
Source File: views.py From kobo-predict with BSD 2-Clause "Simplified" License | 6 votes |
def add_central_engineer(request, pk): obj = get_object_or_404( Project, pk=pk, is_active=True) group = Group.objects.get(name__exact="Reivewer") role_obj = UserRole(project=obj, group=group) scenario = 'Assign' if request.method == 'POST': form = SetProjectRoleForm(data=request.POST, instance=role_obj, request=request) if form.is_valid(): role_obj = form.save(commit=False) user_id = request.POST.get('user') role_obj.user_id = int(user_id) role_obj.save() messages.add_message(request, messages.INFO, 'Reviewer Added') return HttpResponseRedirect(reverse("fieldsight:project-dashboard", kwargs={'pk': obj.pk})) else: form = SetProjectRoleForm(instance=role_obj, request=request,) return render(request, "fieldsight/add_central_engineer.html", {'obj':obj,'form':form, 'scenario':scenario})
Example #7
Source File: read.py From django-cachalot with BSD 3-Clause "New" or "Revised" License | 6 votes |
def setUp(self): super(ReadTestCase, self).setUp() self.group = Group.objects.create(name='test_group') self.group__permissions = list(Permission.objects.all()[:3]) self.group.permissions.add(*self.group__permissions) self.user = User.objects.create_user('user') self.user__permissions = list(Permission.objects.all()[3:6]) self.user.groups.add(self.group) self.user.user_permissions.add(*self.user__permissions) self.admin = User.objects.create_superuser('admin', 'admin@test.me', 'password') self.t1__permission = (Permission.objects.order_by('?') .select_related('content_type')[0]) self.t1 = Test.objects.create( name='test1', owner=self.user, date='1789-07-14', datetime='1789-07-14T16:43:27', permission=self.t1__permission) self.t2 = Test.objects.create( name='test2', owner=self.admin, public=True, date='1944-06-06', datetime='1944-06-06T06:35:00')
Example #8
Source File: views.py From tom_base with GNU General Public License v3.0 | 6 votes |
def get_initial(self): """ Returns the initial data to use for forms on this view. :returns: Dictionary with the following keys: `type`: ``str``: Type of the target to be created `groups`: ``QuerySet<Group>`` Groups available to the current user :rtype: dict """ return { 'type': self.get_target_type(), 'groups': self.request.user.groups.all(), **dict(self.request.GET.items()) }
Example #9
Source File: test_utils.py From django-djangui with GNU General Public License v3.0 | 6 votes |
def test_valid_user(self): user = factories.UserFactory() script = factories.TranslateScriptFactory() d = utils.valid_user(script, user) self.assertTrue(d['valid']) from .. import settings as djangui_settings self.assertEqual('disabled', d['display']) djangui_settings.DJANGUI_SHOW_LOCKED_SCRIPTS = False d = utils.valid_user(script, user) self.assertEqual('hide', d['display']) from django.contrib.auth.models import Group test_group = Group(name='test') test_group.save() script.user_groups.add(test_group) d = utils.valid_user(script, user) self.assertFalse(d['valid']) user.groups.add(test_group) d = utils.valid_user(script, user) self.assertTrue(d['valid'])
Example #10
Source File: config_entity.py From urbanfootprint with GNU General Public License v3.0 | 6 votes |
def config_entity_groups(self): """ Get ConfigEntity-specific groups of the given ConfigEntity. :return: Group objects of the ConfigEntity """ from footprint.client.configuration.fixture import ConfigEntityFixture # Each ConfigEntity class has its own groups according to the configuration # global groups listed in its configuration # Iterate through the configured global groups and create ConfigEntity-specific versions client_fixture = ConfigEntityFixture.resolve_config_entity_fixture(self) # Map the fixture to its ConfigEntity Group # GlobalConfig returns nothing here since the SuperAdmin Group is both its Global Group # and ConfigEntity Group return compact(map( lambda global_group_name: self.config_entity_group(global_group_name), client_fixture.default_config_entity_groups() ))
Example #11
Source File: user_publishing.py From urbanfootprint with GNU General Public License v3.0 | 6 votes |
def _update_or_create_config_entity_groups(config_entity): """ Updates/Creates all the ConfigEntity-specific groups of the given ConfigEntity. :param config_entity: :return: """ from footprint.client.configuration.fixture import ConfigEntityFixture # Each ConfigEntity class has its own groups according to the configuration # global groups listed in its configuration # Iterate through the configured global groups and create ConfigEntity-specific versions # The exception is GlobalConfig, whose ConfigEntity Group is the SuperAdmin Group # It returns nothing here since SuperAdmin is a global Group as well, it doesn't need to be # treated as a ConfigEntity Group client_fixture = ConfigEntityFixture.resolve_config_entity_fixture(config_entity) return map( lambda global_group_name: _update_or_create_config_entity_group(config_entity, global_group_name), client_fixture.default_config_entity_groups())
Example #12
Source File: views.py From urbanfootprint with GNU General Public License v3.0 | 6 votes |
def get_allowed_groups(user, config_entity): """ Returns a list of groups associates with the config entity that the user has permission to access according to ROLE_CHOICES_MAP. """ user_role_key = get_role_key_for_user(user) allowed_groups = [] if user_has_permission_for_config_entity(user, config_entity): if config_entity.key == Keys.GLOBAL_CONFIG_KEY: for allowed_role in ROLE_CHOICES_MAP[user_role_key]: allowed_groups.append(Group.objects.get(name=allowed_role)) else: for gh in config_entity.group_hierarchies.all(): if gh.group: group_role_key = get_role_key_for_group(gh.group) if group_role_key in ROLE_CHOICES_MAP[user_role_key]: allowed_groups.append(gh.group) return allowed_groups
Example #13
Source File: test_explorer_view.py From wagtail with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_nonadmin_at_root(self): # Assign siteeditor permission over no_site_page, so that the deepest-common-ancestor # logic allows them to explore root GroupPagePermission.objects.create( group=Group.objects.get(name="Site-wide editors"), page=self.no_site_page, permission_type='add' ) self.assertTrue(self.client.login(username='siteeditor', password='password')) response = self.client.get(reverse('wagtailadmin_explore_root')) self.assertEqual(response.status_code, 200) # Non-admin should get a simple "create pages as children of the homepage" prompt self.assertContains( response, "Pages created here will not be accessible at any URL. " "To add pages to an existing site, create them as children of the homepage." )
Example #14
Source File: test_explorer_view.py From wagtail with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_nonadmin_at_non_site_page(self): # Assign siteeditor permission over no_site_page GroupPagePermission.objects.create( group=Group.objects.get(name="Site-wide editors"), page=self.no_site_page, permission_type='add' ) self.assertTrue(self.client.login(username='siteeditor', password='password')) response = self.client.get(reverse('wagtailadmin_explore', args=(self.no_site_page.id, ))) self.assertEqual(response.status_code, 200) # Non-admin should get a warning about unroutable pages self.assertContains( response, ( "There is no site record for this location. " "Pages created here will not be accessible at any URL." ) )
Example #15
Source File: tests.py From wagtail with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_group_create_adding_permissions(self): response = self.post({ 'name': "test group", 'page_permissions-0-page': ['1'], 'page_permissions-0-permission_types': ['edit', 'publish'], 'page_permissions-TOTAL_FORMS': ['1'], 'document_permissions-0-collection': [Collection.get_first_root_node().pk], 'document_permissions-0-permissions': [self.add_doc_permission.pk], 'document_permissions-TOTAL_FORMS': ['1'], }) self.assertRedirects(response, reverse('wagtailusers_groups:index')) # The test group now exists, with two page permissions # and one 'add document' collection permission new_group = Group.objects.get(name='test group') self.assertEqual(new_group.page_permissions.all().count(), 2) self.assertEqual( new_group.collection_permissions.filter(permission=self.add_doc_permission).count(), 1 )
Example #16
Source File: tests.py From wagtail with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_can_submit_blank_permission_form(self): # the formsets for page / collection permissions should gracefully # handle (and ignore) forms that have been left entirely blank response = self.post({ 'name': "test group", 'page_permissions-0-page': [''], 'page_permissions-TOTAL_FORMS': ['1'], 'document_permissions-0-collection': [''], 'document_permissions-TOTAL_FORMS': ['1'], }) self.assertRedirects(response, reverse('wagtailusers_groups:index')) # The test group now exists, with no page / document permissions new_group = Group.objects.get(name='test group') self.assertEqual(new_group.page_permissions.all().count(), 0) self.assertEqual( new_group.collection_permissions.filter(permission=self.add_doc_permission).count(), 0 )
Example #17
Source File: groups.py From wagtail with BSD 3-Clause "New" or "Revised" License | 6 votes |
def post(self, request, *args, **kwargs): """ Handle POST requests: instantiate a form instance with the passed POST variables and then check if it's valid. """ # Create an object now so that the permission panel forms have something to link them against self.object = Group() form = self.get_form() permission_panels = self.get_permission_panel_forms() if form.is_valid() and all(panel.is_valid() for panel in permission_panels): response = self.form_valid(form) for panel in permission_panels: panel.save() return response else: return self.form_invalid(form)
Example #18
Source File: views.py From urbanfootprint with GNU General Public License v3.0 | 6 votes |
def get_config_entities_for_user(user): """Returns the ConfigEntity objects corresponding to the group a user belongs to.""" global_config_group_names = [UserGroupKey.SUPERADMIN, UserGroupKey.ADMIN, UserGroupKey.MANAGER, UserGroupKey.USER] user_config_entities = [] for group in user.groups.all(): if group.group_hierarchy: if group.group_hierarchy.config_entity: user_config_entities.append(group.group_hierarchy.config_entity) elif group.id in Group.objects.filter(name__in=global_config_group_names).values_list('id', flat=True): user_config_entities.append(GlobalConfig.objects.get()) return user_config_entities
Example #19
Source File: test_schema.py From djangoql with MIT License | 6 votes |
def test_invalid_config(self): try: IncludeExcludeSchema(Group) self.fail('Invalid schema with include & exclude raises no error') except DjangoQLSchemaError: pass try: IncludeUserGroupSchema(Book) self.fail('Schema was initialized with a model excluded from it') except DjangoQLSchemaError: pass try: IncludeUserGroupSchema(User()) self.fail('Schema was initialized with an instance of a model') except DjangoQLSchemaError: pass
Example #20
Source File: admin.py From Servo with BSD 2-Clause "Simplified" License | 6 votes |
def edit_group(request, pk=None): title = _(u'Edit Group') object_list = Group.objects.all() if pk is None: group = Group() form = GroupForm(instance=group) else: group = Group.objects.get(pk=pk) title = group.name form = GroupForm(instance=group) if request.method == 'POST': form = GroupForm(request.POST, instance=group) if form.is_valid(): form.save() messages.success(request, _(u'Group saved')) return redirect(list_groups) return render(request, 'admin/users/group_form.html', locals())
Example #21
Source File: test_models_page_role.py From richie with MIT License | 6 votes |
def test_models_page_role_group_and_folder(self, *_): """ A group and a folder should be automatically created the first time the page role is saved. """ page = PageFactory(title__title="My page") role = PageRole(page=page, role="ADMIN") with self.assertRaises(ObjectDoesNotExist): self.assertEqual(role.group._meta.model, Group) with self.assertRaises(ObjectDoesNotExist): self.assertEqual(role.folder._meta.model, Folder) # Now save the object and check that the group and folder fields were populated role.save() self.assertEqual(role.group._meta.model, Group) self.assertEqual(role.folder._meta.model, Folder) self.assertEqual(role.group.name, "Admin | My page") self.assertEqual(role.folder.name, "Admin | My page")
Example #22
Source File: test_multi_model_form_view.py From django-shapeshifter with Apache License 2.0 | 6 votes |
def test_multiple_forms_success_mixin_method(request_factory): """Multiple forms should be rendered to the template""" request = request_factory().post( "/", data={ "userform-first_name": "Katherine", "userform-last_name": "Johnson", "userform-username": "KJohnson", "groupform-name": "Admins", }, ) request = get_session_request(request) with mock.patch.object(Group, "save"), mock.patch.object(User, "save"): MembershipSuccessMethod.as_view()(request) assert "this is a method success message" in [ m.message for m in request._messages._queued_messages ]
Example #23
Source File: test_multi_model_form_view.py From django-shapeshifter with Apache License 2.0 | 6 votes |
def test_multiple_forms_success_mixin(request_factory): """Multiple forms should be rendered to the template""" request = request_factory().post( "/", data={ "userform-first_name": "Katherine", "userform-last_name": "Johnson", "userform-username": "KJohnson", "groupform-name": "Admins", }, ) request = get_session_request(request) with mock.patch.object(Group, "save"), mock.patch.object(User, "save"): Membership.as_view()(request) assert "this is a success message" in [ m.message for m in request._messages._queued_messages ]
Example #24
Source File: test_explorer_view.py From wagtail with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_bad_permissions_at_site_page(self): # Adjust siteeditor's permission so that they have permission over no_site_page # instead of site_page Group.objects.get(name="Site-wide editors").page_permissions.update(page_id=self.no_site_page.id) self.assertTrue(self.client.login(username='siteeditor', password='password')) response = self.client.get(reverse('wagtailadmin_explore', args=(self.site_page.id, ))) # Users without permission to explore here should be redirected to their explorable root. self.assertEqual( (response.status_code, response['Location']), (302, reverse('wagtailadmin_explore', args=(self.no_site_page.pk, ))) )
Example #25
Source File: views.py From kobo-predict with BSD 2-Clause "Simplified" License | 5 votes |
def alter_org_status(request, pk): try: obj = Organization.objects.get(pk=int(pk)) # alter status method on custom user if obj.is_active: obj.is_active = False messages.info(request, 'Organization {0} Deactivated.'.format(obj.name)) else: obj.is_active = True messages.info(request, 'Organization {0} Activated.'.format(obj.name)) obj.save() except: messages.info(request, 'Organization {0} not found.'.format(obj.name)) return HttpResponseRedirect(reverse('fieldsight:organizations-list')) # # @login_required # @group_required('admin') # def add_org_admin_old(request, pk): # obj = get_object_or_404( # Organization, id=pk) # if request.method == 'POST': # form = SetOrgAdminForm(request.POST) # user = int(form.data.get('user')) # group = Group.objects.get(name__exact="Organization Admin") # role = UserRole(user_id=user, group=group, organization=obj) # role.save() # messages.add_message(request, messages.INFO, 'Organization Admin Added') # return HttpResponseRedirect(reverse('fieldsight:organizations-list')) # else: # form = SetOrgAdminForm(instance=obj) # return render(request, "fieldsight/add_admin.html", {'obj':obj,'form':form})
Example #26
Source File: shortcuts.py From resolwe with Apache License 2.0 | 5 votes |
def get_groups_with_perms(obj, attach_perms=False): """Return queryset of all ``Group`` objects with *any* object permissions for the given ``obj``.""" ctype = get_content_type(obj) group_model = get_group_obj_perms_model(obj) if not attach_perms: # It's much easier without attached perms so we do it first if that is the case group_rel_name = group_model.group.field.related_query_name() if group_model.objects.is_generic(): group_filters = { "%s__content_type" % group_rel_name: ctype, "%s__object_pk" % group_rel_name: obj.pk, } else: group_filters = {"%s__content_object" % group_rel_name: obj} return Group.objects.filter(**group_filters).distinct() else: group_perms_mapping = defaultdict(list) groups_with_perms = get_groups_with_perms(obj) queryset = group_model.objects.filter( group__in=groups_with_perms ).prefetch_related("group", "permission") if group_model is GroupObjectPermission: queryset = queryset.filter(object_pk=obj.pk, content_type=ctype) else: queryset = queryset.filter(content_object_id=obj.pk) for group_perm in queryset: group_perms_mapping[group_perm.group].append(group_perm.permission.codename) return dict(group_perms_mapping)
Example #27
Source File: tests.py From wagtail with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_group_edit(self): response = self.post({'name': "test group edited"}) # Should redirect back to index self.assertRedirects(response, reverse('wagtailusers_groups:index')) # Check that the group was edited group = Group.objects.get(pk=self.test_group.pk) self.assertEqual(group.name, 'test group edited')
Example #28
Source File: test_collection_privacy.py From wagtail with BSD 3-Clause "New" or "Revised" License | 5 votes |
def setUp(self): self.fake_file = ContentFile(b"A boring example document") self.fake_file.name = 'test.txt' self.password_collection = Collection.objects.get(name='Password protected') self.login_collection = Collection.objects.get(name='Login protected') self.group_collection = Collection.objects.get(name='Group protected') self.view_restriction = CollectionViewRestriction.objects.get(collection=self.password_collection) self.event_editors_group = Group.objects.get(name='Event editors')
Example #29
Source File: models.py From wagtail with BSD 3-Clause "New" or "Revised" License | 5 votes |
def __str__(self): return "Group %d ('%s') has permission '%s' on collection %d ('%s')" % ( self.group.id, self.group, self.permission, self.collection.id, self.collection )
Example #30
Source File: models.py From wagtail with BSD 3-Clause "New" or "Revised" License | 5 votes |
def __str__(self): return "Group %d ('%s') has permission '%s' on page %d ('%s')" % ( self.group.id, self.group, self.permission_type, self.page.id, self.page )