Python django.contrib.auth.models.Group() Examples

The following are 30 code examples for showing how to use django.contrib.auth.models.Group(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

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
Project: Servo   Author: fpsw   File: admin.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 2
Project: django-river   Author: javrasya   File: config.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 3
Project: resolwe   Author: genialis   File: shortcuts.py    License: Apache License 2.0 6 votes vote down vote up
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 4
Project: kobo-predict   Author: awemulya   File: views.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
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
Project: kobo-predict   Author: awemulya   File: views.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 6
Project: kobo-predict   Author: awemulya   File: views.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
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
Project: django-cachalot   Author: noripyt   File: read.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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
Project: tom_base   Author: TOMToolkit   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
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
Project: django-djangui   Author: Chris7   File: test_utils.py    License: GNU General Public License v3.0 6 votes vote down vote up
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
Project: urbanfootprint   Author: CalthorpeAnalytics   File: config_entity.py    License: GNU General Public License v3.0 6 votes vote down vote up
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
Project: urbanfootprint   Author: CalthorpeAnalytics   File: user_publishing.py    License: GNU General Public License v3.0 6 votes vote down vote up
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
Project: urbanfootprint   Author: CalthorpeAnalytics   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
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
Project: urbanfootprint   Author: CalthorpeAnalytics   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 14
Project: wagtail   Author: wagtail   File: test_explorer_view.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 15
Project: wagtail   Author: wagtail   File: test_explorer_view.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 16
Project: wagtail   Author: wagtail   File: tests.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 17
Project: wagtail   Author: wagtail   File: tests.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 18
Project: wagtail   Author: wagtail   File: groups.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 19
Project: djangoql   Author: ivelum   File: test_schema.py    License: MIT License 6 votes vote down vote up
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
Project: richie   Author: openfun   File: test_models_page_role.py    License: MIT License 6 votes vote down vote up
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 21
Project: django-shapeshifter   Author: kennethlove   File: test_multi_model_form_view.py    License: Apache License 2.0 6 votes vote down vote up
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 22
Project: django-shapeshifter   Author: kennethlove   File: test_multi_model_form_view.py    License: Apache License 2.0 6 votes vote down vote up
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
Project: django-shapeshifter   Author: kennethlove   File: test_multi_model_form_view.py    License: Apache License 2.0 6 votes vote down vote up
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 24
Project: Servo   Author: fpsw   File: admin.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def list_groups(request):
    object_list = Group.objects.all()
    title = _('Users & Groups')

    return render(request, 'admin/users/groups.html', locals()) 
Example 25
Project: Servo   Author: fpsw   File: admin.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def delete_group(request, pk):
    group = get_object_or_404(Group, pk=pk)

    if request.method == "POST":
        group.delete()
        messages.success(request, _("Group deleted"))
        return redirect(list_groups)

    data = {'action': request.path}

    return render(request, "admin/users/delete_group.html", data) 
Example 26
Project: donation-tracker   Author: GamesDoneQuick   File: test_me.py    License: Apache License 2.0 5 votes vote down vote up
def test_user_with_group_permissions(self):
        group = Group.objects.create(name='Test Group')
        group.permissions.add(Permission.objects.get(codename='add_user'))
        group.user_set.add(self.request.user)
        self.assertEqual(
            self.parseJSON(tracker.views.me(self.request)),
            {'username': 'test', 'permissions': ['auth.add_user']},
        ) 
Example 27
Project: seqr   Author: macarthur-lab   File: models.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def save(self, *args, **kwargs):
        """Override the save method and create user permissions groups + add the created_by user.

        This could be done with signals, but seems cleaner to do it this way.
        """
        being_created = not self.pk

        if being_created:
            # create user groups
            self.owners_group = Group.objects.create(name="%s_%s_%s" % (_slugify(self.name.strip())[:30], 'owners', uuid.uuid4()))
            self.can_edit_group = Group.objects.create(name="%s_%s_%s" % (_slugify(self.name.strip())[:30], 'can_edit', uuid.uuid4()))
            self.can_view_group = Group.objects.create(name="%s_%s_%s" % (_slugify(self.name.strip())[:30], 'can_view', uuid.uuid4()))

        super(Project, self).save(*args, **kwargs)

        if being_created:
            assign_perm(user_or_group=self.owners_group, perm=IS_OWNER, obj=self)
            assign_perm(user_or_group=self.owners_group, perm=CAN_EDIT, obj=self)
            assign_perm(user_or_group=self.owners_group, perm=CAN_VIEW, obj=self)

            assign_perm(user_or_group=self.can_edit_group, perm=CAN_EDIT, obj=self)
            assign_perm(user_or_group=self.can_edit_group, perm=CAN_VIEW, obj=self)

            assign_perm(user_or_group=self.can_view_group, perm=CAN_VIEW, obj=self)

            # add the user that created this Project to all permissions groups
            user = self.created_by
            if user and not user.is_staff:  # staff have access to all resources anyway
                user.groups.add(self.owners_group, self.can_edit_group, self.can_view_group) 
Example 28
Project: resolwe   Author: genialis   File: shortcuts.py    License: Apache License 2.0 5 votes vote down vote up
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 29
Project: kobo-predict   Author: awemulya   File: views.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
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 30
Project: kobo-predict   Author: awemulya   File: views.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def post(self, request):
        organization = get_object_or_404(Organization, id=id)
        group = Group.objects.get(name__exact="Organization Admin")
        role_obj = UserRole(organization=organization, group=group)
        form = AssignOrgAdmin(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, 'Organization Admin Added')
            return HttpResponseRedirect(reverse("fieldsight:organizations-dashboard", kwargs={'pk': id}))