当前位置: 首页>>代码示例>>Python>>正文


Python Group.DoesNotExist方法代码示例

本文整理汇总了Python中django.contrib.auth.models.Group.DoesNotExist方法的典型用法代码示例。如果您正苦于以下问题:Python Group.DoesNotExist方法的具体用法?Python Group.DoesNotExist怎么用?Python Group.DoesNotExist使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.contrib.auth.models.Group的用法示例。


在下文中一共展示了Group.DoesNotExist方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_context_data

# 需要导入模块: from django.contrib.auth.models import Group [as 别名]
# 或者: from django.contrib.auth.models.Group import DoesNotExist [as 别名]
def get_context_data(self, **kwargs):
        """Add context as to whether this is a reviewer or speaker."""
        context = super(ProposalDetailView, self).get_context_data(**kwargs)
        if _is_reviewer_or_superuser(self.request.user):
            context["actor"] = "reviewer"
        for speaker in self.get_object().speakers():
            if self.request.user == speaker.user:
                context["actor"] = "speaker"
        try:
            vote = ProposalVote.objects.get(
                proposal=self.get_object(), voter=self.request.user
            )
            context["vote_form"] = ProposalVoteForm(instance=vote)
            context["existing_vote"] = True
        except ProposalVote.DoesNotExist:
            context["vote_form"] = ProposalVoteForm
        context["feedback_form"] = ProposalFeedbackForm
        return context 
开发者ID:pydata,项目名称:conf_site,代码行数:20,代码来源:__init__.py

示例2: get_countries

# 需要导入模块: from django.contrib.auth.models import Group [as 别名]
# 或者: from django.contrib.auth.models.Group import DoesNotExist [as 别名]
def get_countries(self, filter_for_book=False, filter_for_supervisor=False):
        book_filter = Q(in_book=True, visibility__visible_in_book=True)
        online_filter = Q(visibility__visible_online_public=True)
        places = Place.available_objects.filter(
            book_filter if filter_for_book else
            ((book_filter | online_filter) if filter_for_supervisor else online_filter)
        )
        groups = Group.objects.exclude(user=None)
        countries = sort_by(["name"], {p.country for p in places})
        for country in countries:
            try:
                group = groups.get(name=country.code)
                country.supervisors = sorted(
                    user.profile for user in group.user_set.filter(
                        is_active=True, profile__isnull=False, profile__deleted_on__isnull=True)
                )
            except Group.DoesNotExist:
                pass
            places_for_country = places.filter(country=country)
            country.place_count = places_for_country.count()
            country.checked_count = places_for_country.filter(checked=True).count()
            country.only_confirmed_count = places_for_country.filter(
                confirmed=True, checked=False).count()
        return countries 
开发者ID:tejoesperanto,项目名称:pasportaservo,代码行数:26,代码来源:views.py

示例3: profile_view

# 需要导入模块: from django.contrib.auth.models import Group [as 别名]
# 或者: from django.contrib.auth.models.Group import DoesNotExist [as 别名]
def profile_view(request, user_id):
    try:
        user = User.objects.get(pk=user_id)
    except User.DoesNotExist:
        return redirect("/taskManager/dashboard")

    if request.user.groups.filter(name='admin_g').exists():
        role = "Admin"
    elif request.user.groups.filter(name='project_managers').exists():
        role = "Project Manager"
    else:
        role = "Team Member"

    sorted_projects = Project.objects.filter(
        users_assigned=request.user.id).order_by('title')

    return render(request, 'taskManager/profile_view.html',
                  {'user': user, 'role': role, 'project_list': sorted_projects}) 
开发者ID:python-security,项目名称:pyt,代码行数:20,代码来源:views.py

示例4: check_is_member_or_maintainer

# 需要导入模块: from django.contrib.auth.models import Group [as 别名]
# 或者: from django.contrib.auth.models.Group import DoesNotExist [as 别名]
def check_is_member_or_maintainer(user, group_name):
    """
    Check if a user is a member or maintainer of the a group
    Args:
        user: User_name
        group_name: Group_name

    Returns:

    """
    try:
        group = Group.objects.get(name = group_name)
        bgroup = BossGroup.objects.get(group=group)
        if user.has_perm("maintain_group", bgroup) or group.user_set.filter(id=user.id).exists():
            return True
        else:
            return False
    except (Group.DoesNotExist , BossGroup.DoesNotExist) as e:
        return BossError("{} does not exist".format(group_name), ErrorCodes.RESOURCE_NOT_FOUND) 
开发者ID:jhuapl-boss,项目名称:boss,代码行数:21,代码来源:permissions.py

示例5: init_user

# 需要导入模块: from django.contrib.auth.models import Group [as 别名]
# 或者: from django.contrib.auth.models.Group import DoesNotExist [as 别名]
def init_user(user):
    """
    给用户关联默认资源组和权限组
    :param user:
    :return:
    """
    # 添加到默认权限组
    default_auth_group = SysConfig().get('default_auth_group', '')
    if default_auth_group:
        try:
            group = Group.objects.get(name=default_auth_group)
            user.groups.add(group)
        except Group.DoesNotExist:
            logger.info(f'无name为[{default_auth_group}]的权限组,无法默认关联,请到系统设置进行配置')
    # 添加到默认资源组
    default_resource_group = SysConfig().get('default_resource_group', '')
    if default_resource_group:
        try:
            user.resource_group.add(ResourceGroup.objects.get(group_name=default_resource_group))
        except ResourceGroup.DoesNotExist:
            logger.info(f'无name为[{default_resource_group}]的资源组,无法默认关联,请到系统设置进行配置') 
开发者ID:hhyo,项目名称:Archery,代码行数:23,代码来源:auth.py

示例6: fetch_group

# 需要导入模块: from django.contrib.auth.models import Group [as 别名]
# 或者: from django.contrib.auth.models.Group import DoesNotExist [as 别名]
def fetch_group(query):
    """Get group by ``pk`` or ``name``. Raise error if it doesn't exist."""
    group_filter = {"pk": query} if query.isdigit() else {"name": query}

    try:
        return Group.objects.get(**group_filter)
    except Group.DoesNotExist:
        raise exceptions.ParseError("Unknown group: {}".format(query)) 
开发者ID:genialis,项目名称:resolwe,代码行数:10,代码来源:utils.py

示例7: render

# 需要导入模块: from django.contrib.auth.models import Group [as 别名]
# 或者: from django.contrib.auth.models.Group import DoesNotExist [as 别名]
def render(self, context):
        user = template.resolve_variable('user', context)

        if not user.is_authenticated():
            return self.nodelist_false.render(context)

        allowed = False
        for checkgroup in self.groups:

            if checkgroup.startswith('"') and checkgroup.endswith('"'):
                checkgroup = checkgroup[1:-1]

            if checkgroup.startswith("'") and checkgroup.endswith("'"):
                checkgroup = checkgroup[1:-1]

            try:
                group = Group.objects.get(name=checkgroup)
            except Group.DoesNotExist:
                break

            if group in user.groups.all():
                allowed = True
                break

        if allowed:
            return self.nodelist_true.render(context)
        else:
            return self.nodelist_false.render(context) 
开发者ID:awemulya,项目名称:kobo-predict,代码行数:30,代码来源:filters.py

示例8: _is_reviewer_or_superuser

# 需要导入模块: from django.contrib.auth.models import Group [as 别名]
# 或者: from django.contrib.auth.models.Group import DoesNotExist [as 别名]
def _is_reviewer_or_superuser(user):
    """Check if user is in Reviewers group or is superuser."""
    if user.is_superuser:
        return True
    # Raise an exception if the Reviewers group does not
    # exist, because this is a critical problem.
    try:
        reviewers_group = Group.objects.get(name="Reviewers")
    except Group.DoesNotExist:
        raise Exception("Reviewers user group does not exist.")
    return reviewers_group in user.groups.all() 
开发者ID:pydata,项目名称:conf_site,代码行数:13,代码来源:__init__.py

示例9: test_func

# 需要导入模块: from django.contrib.auth.models import Group [as 别名]
# 或者: from django.contrib.auth.models.Group import DoesNotExist [as 别名]
def test_func(self):
        """Check if user can access reviewing section."""
        # If allow_speakers is enabled, speakers get access.
        if self.allow_speakers:
            # Test whether user is one of the proposal's speakers.
            try:
                proposal = Proposal.objects.get(pk=self.kwargs["pk"])
                for speaker in proposal.speakers():
                    if self.request.user == speaker.user:
                        return True
            except Proposal.DoesNotExist:
                pass

        return _is_reviewer_or_superuser(self.request.user) 
开发者ID:pydata,项目名称:conf_site,代码行数:16,代码来源:__init__.py

示例10: get

# 需要导入模块: from django.contrib.auth.models import Group [as 别名]
# 或者: from django.contrib.auth.models.Group import DoesNotExist [as 别名]
def get(self, request, *args, **kwargs):
        try:
            self.proposal_kind = ProposalKind.objects.get(slug=kwargs["kind"])
        except ProposalKind.DoesNotExist:
            raise Http404
        return super().get(request, *args, **kwargs) 
开发者ID:pydata,项目名称:conf_site,代码行数:8,代码来源:__init__.py

示例11: user_score

# 需要导入模块: from django.contrib.auth.models import Group [as 别名]
# 或者: from django.contrib.auth.models.Group import DoesNotExist [as 别名]
def user_score(proposal, user):
    """For the selected proposal, display the current user's review score."""
    # Try to retrieve score from cache.
    score_cache_key = proposalvote_score_cache_key(proposal, user)
    cached_score = cache.get(score_cache_key)
    if cached_score:
        return cached_score
    try:
        uncached_score = ProposalVote.objects.get(
            proposal=proposal, voter=user
        ).get_numeric_score_display()
    except ProposalVote.DoesNotExist:
        uncached_score = " "
    cache.set(score_cache_key, uncached_score, settings.CACHE_TIMEOUT_LONG)
    return uncached_score 
开发者ID:pydata,项目名称:conf_site,代码行数:17,代码来源:review_tags.py

示例12: reset_password

# 需要导入模块: from django.contrib.auth.models import Group [as 别名]
# 或者: from django.contrib.auth.models.Group import DoesNotExist [as 别名]
def reset_password(request):

    if request.method == 'POST':

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

        try:
            userprofile = UserProfile.objects.get(reset_token = reset_token)
            if timezone.now() > userprofile.reset_token_expiration:
                # Reset the token and move on
                userprofile.reset_token_expiration = timezone.now()
                userprofile.reset_token = ''
                userprofile.save()
                return redirect('/taskManager/')

        except UserProfile.DoesNotExist:
            messages.warning(request, 'Invalid password reset token')
            return render(request, 'taskManager/reset_password.html')

        new_password = request.POST.get('new_password')
        confirm_password = request.POST.get('confirm_password')
        if new_password != confirm_password:
            messages.warning(request, 'Passwords do not match')
            return render(request, 'taskManager/reset_password.html')

        # Reset the user's password + remove the tokens
        userprofile.user.set_password(new_password)
        userprofile.reset_token = ''
        userprofile.reset_token_expiration = timezone.now()
        userprofile.user.save()
        userprofile.save()

        messages.success(request, 'Password has been successfully reset')
        return redirect('/taskManager/login')

    return render(request, 'taskManager/reset_password.html')

# Vuln: Username Enumeration 
开发者ID:python-security,项目名称:pyt,代码行数:40,代码来源:views.py

示例13: forgot_password

# 需要导入模块: from django.contrib.auth.models import Group [as 别名]
# 或者: from django.contrib.auth.models.Group import DoesNotExist [as 别名]
def forgot_password(request):

    if request.method == 'POST':
        t_email = request.POST.get('email')

        try:
            reset_user = User.objects.get(email=t_email)

            # Generate secure random 6 digit number
            res = ""
            nums = [x for x in os.urandom(6)]
            for x in nums:
                res = res + str(x)

            reset_token = res[:6]
            reset_user.userprofile.reset_token = reset_token
            reset_user.userprofile.reset_token_expiration = timezone.now() + datetime.timedelta(minutes=10)
            reset_user.userprofile.save()
            reset_user.save()

            reset_user.email_user(
                "Reset your password",
                "You can reset your password at /taskManager/reset_password/. Use \"{}\" as your token. This link will only work for 10 minutes.".format(reset_token))

            messages.success(request, 'Check your email for a reset token')
            return redirect('/taskManager/reset_password')
        except User.DoesNotExist:
            messages.warning(request, 'Check your email for a reset token')

    return render(request, 'taskManager/forgot_password.html')

# A8: Cross Site Request Forgery (CSRF) 
开发者ID:python-security,项目名称:pyt,代码行数:34,代码来源:views.py

示例14: add_permissions_admin_group

# 需要导入模块: from django.contrib.auth.models import Group [as 别名]
# 或者: from django.contrib.auth.models.Group import DoesNotExist [as 别名]
def add_permissions_admin_group(obj):
        """
        Grant permissions to the admin group for an object
        Args:

            obj: Object that we are assigning permission for

        Returns:
            None
        """
        # Get the type of model
        try:
            admin_group, created = Group.objects.get_or_create(name="admin")
            if created:
                admin_user = User.objects.get(username='bossadmin')
                bgroup = BossGroup.objects.create(group=admin_group, creator=admin_user)
                
            ct = ContentType.objects.get_for_model(obj)
            assign_perm('read', admin_group, obj)
            assign_perm('add', admin_group, obj)
            assign_perm('update', admin_group, obj)
            assign_perm('delete', admin_group, obj)
            assign_perm('assign_group', admin_group, obj)
            assign_perm('remove_group', admin_group, obj)
            if ct.model == 'channel':
                assign_perm('add_volumetric_data', admin_group, obj)
                assign_perm('read_volumetric_data', admin_group, obj)
                assign_perm('delete_volumetric_data', admin_group, obj)

        except Group.DoesNotExist:
            raise BossError("Cannot assign permissions to the admin group because the group does not exist",
                            ErrorCodes.GROUP_NOT_FOUND) 
开发者ID:jhuapl-boss,项目名称:boss,代码行数:34,代码来源:permissions.py

示例15: get

# 需要导入模块: from django.contrib.auth.models import Group [as 别名]
# 或者: from django.contrib.auth.models.Group import DoesNotExist [as 别名]
def get(self, request, group_name, user_name=None):
        """
        Gets the membership status of a user for a group
        Args:
           request: Django rest framework request
           group_name: Group name from the request
           user_name: User name from the request

       Returns:
           bool : True if the user is a member of the group

        """
        try:
            group = Group.objects.get(name=group_name)

            # Check for permissions. The logged in user has to be a member or group maintainer
            if not check_is_member_or_maintainer(request.user, group_name):
                return BossHTTPError('The user {} is not a member or maintainer of the group {} '
                                     .format(request.user.username, group_name),
                                     ErrorCodes.MISSING_PERMISSION)
            if user_name is None:
                # Return all users for the group
                list_users = group.user_set.all().values_list('username', flat=True)
                list_users = [name for name in list_users]
                data = {"members": list_users}
            else:
                # Both group name and user name are specified. Return the membership status for the user
                usr = User.objects.get(username=user_name)
                status = group.user_set.filter(id=usr.id).exists()
                data = {"result": status}

            return Response(data, status=200)
        except Group.DoesNotExist:
            return BossGroupNotFoundError(group_name)
        except User.DoesNotExist:
            return BossUserNotFoundError(user_name) 
开发者ID:jhuapl-boss,项目名称:boss,代码行数:38,代码来源:views_group.py


注:本文中的django.contrib.auth.models.Group.DoesNotExist方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。