Python django.core.urlresolvers 模块,resolve() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.core.urlresolvers.resolve()

项目:ecs_sclm    作者:meaningful    | 项目源码 | 文件源码
def get_admin_site(current_app):
    """
    Method tries to get actual admin.site class, if any custom admin sites
    were used. Couldn't find any other references to actual class other than
    in func_closer dict in index() func returned by resolver.
    """
    try:
        resolver_match = resolve(reverse('%s:index' % current_app))
        # Django 1.9 exposes AdminSite instance directly on view function
        if hasattr(resolver_match.func, 'admin_site'):
            return resolver_match.func.admin_site

        for func_closure in resolver_match.func.__closure__:
            if isinstance(func_closure.cell_contents, AdminSite):
                return func_closure.cell_contents
    except:
        pass
    return admin.site
项目:ecs_sclm    作者:meaningful    | 项目源码 | 文件源码
def process_url(self, url, app=None):
        """
        Try to guess if it is absolute url or named
        """
        if url is None:
            return ''

        if not url or '/' in url:
            return url

        # Model link, ex: 'auth.user'
        if '.' in url:
            url_parts = url.split('.')
            model = self.make_model_from_native(url_parts[1], url_parts[0])
            if model:
                if app:
                    app['model'] = model
                return model['url']

        # Try to resolve as named url, ex: 'admin:index'
        try:
            return reverse(url)
        except:
            return url
项目:Server    作者:malaonline    | 项目源码 | 文件源码
def menu_active(context, *args, **kwargs):
    '''
    only menu_active check, do not permissions check
    '''
    request = context['request']
    active_style = 'menu_active'
    display_style = ''
    try:
        resolver_match = urlresolvers.resolve(request.path_info)
        url_name = resolver_match.url_name
        namespaces = resolver_match.namespaces
        for arg in args:
            tmp_path = '.'.join(namespaces)
            if len(tmp_path) > 0:
                tmp_path += ':' + url_name
            else:
                tmp_path = url_name
            if tmp_path == arg:
                return active_style + ' ' + display_style
    except:
        return display_style

    return display_style
项目:DCRM    作者:82Flex    | 项目源码 | 文件源码
def get_admin_site(current_app):
    """
    Method tries to get actual admin.site class, if any custom admin sites
    were used. Couldn't find any other references to actual class other than
    in func_closer dict in index() func returned by resolver.
    """
    try:
        resolver_match = resolve(reverse('%s:index' % current_app))
        # Django 1.9 exposes AdminSite instance directly on view function
        if hasattr(resolver_match.func, 'admin_site'):
            return resolver_match.func.admin_site

        for func_closure in resolver_match.func.__closure__:
            if isinstance(func_closure.cell_contents, AdminSite):
                return func_closure.cell_contents
    except:
        pass
    from django.contrib import admin
    return admin.site
项目:dart    作者:lmco    | 项目源码 | 文件源码
def get_context_data(self, **kwargs):
        context = super(EditMissionTestView, self).get_context_data(**kwargs)
        context['action'] = reverse('mission-test-edit', kwargs={'pk': self.get_object().id,
                                                                 'mission': self.kwargs['mission']})
        mission_model = Mission.objects.get(id=self.kwargs['mission'])
        context['this_mission'] = mission_model

        context['display_navbar_save_button'] = True
        context['is_read_only'] = resolve(self.request.path_info).url_name == 'mission-test-view'
        if self.request.GET.get('scrollPos'):
            try:
                context['scrollPos'] = int(self.request.GET.get('scrollPos'))
            except ValueError:
                logger.exception('URL Parameter scrollPos invalid (not an int); setting to None. '
                                 '(Logged in user: {user})'.format(user=self.request.user.username or "**Anonymous**"))
                context['scrollPos'] = None
        return context
项目:wagtail-startproject    作者:leukeleu    | 项目源码 | 文件源码
def assert_model_resolves_expected_view(self, obj, expected_view):
        """Check if expected view is called for the given obj's absolute_url

        In some cases an earlier defined url in the urls.py catches the request.
        For class-based views give function returned by `as_view()` as expected_view.

        """
        url = obj.get_absolute_url()

        try:
            view, args, kwargs = resolve(url)
        except Resolver404:
            raise AssertionError('Unable to resolve the url for the object: "{url}"'.format(url=url))

        self.assertEqual(
            expected_view,
            view,
            msg="Url resolves to {view} instead of the expected {expected_view}.".format(view=view, expected_view=expected_view)
        )
项目:tumanov_castleoaks    作者:Roamdev    | 项目源码 | 文件源码
def get_admin_site(current_app):
    """
    Method tries to get actual admin.site class, if any custom admin sites
    were used. Couldn't find any other references to actual class other than
    in func_closer dict in index() func returned by resolver.
    """
    try:
        resolver_match = resolve(reverse('%s:index' % current_app))
        # Django 1.9 exposes AdminSite instance directly on view function
        if hasattr(resolver_match.func, 'admin_site'):
            return resolver_match.func.admin_site

        for func_closure in resolver_match.func.__closure__:
            if isinstance(func_closure.cell_contents, AdminSite):
                return func_closure.cell_contents
    except:
        pass
    return admin.site
项目:tumanov_castleoaks    作者:Roamdev    | 项目源码 | 文件源码
def process_url(self, url, app=None):
        """
        Try to guess if it is absolute url or named
        """
        if url is None:
            return ''

        if not url or '/' in url:
            return url

        # Model link, ex: 'auth.user'
        if '.' in url:
            url_parts = url.split('.')
            model = self.make_model_from_native(url_parts[1], url_parts[0])
            if model:
                if app:
                    app['model'] = model
                return model['url']

        # Try to resolve as named url, ex: 'admin:index'
        try:
            return reverse(url)
        except:
            return url
项目:cocreate    作者:ngageoint    | 项目源码 | 文件源码
def chooseRedirect(request, playground_id, sandbox_id):
    """
    Determine whether we redirect to the playground detail or sandbox detail
    """
    next = request.META.get('HTTP_REFERER', None) or None

    redirectToPlayground = True

    if next is not None:
        match = resolve(urlparse(next)[2])

        if match is not None:
            if match.view_name.startswith("sandbox"):
                redirectToPlayground = False

    if redirectToPlayground:
        return HttpResponseRedirect(reverse("playground", args=[playground_id]))
    else:
        return HttpResponseRedirect(reverse("sandbox-details", args=[playground_id, sandbox_id]))
项目:kolibri    作者:learningequality    | 项目源码 | 文件源码
def _kolibri_bootstrap_helper(context, base_name, api_resource, route, **kwargs):
    reversal = dict()
    kwargs_check = 'kwargs_'
    # remove prepended string and matching items from kwargs
    for key in list(kwargs.keys()):
        if kwargs_check in key:
            item = kwargs.pop(key)
            key = re.sub(kwargs_check, '', key)
            reversal[key] = item
    view, view_args, view_kwargs = resolve(reverse('{0}-{1}'.format(base_name, route), kwargs=reversal))
    # switch out None temporarily because invalid filtering and caching can occur
    _replace_dict_values(None, str(''), kwargs)
    request = copy.copy(context['request'])
    request.GET = request.GET.copy()
    for key in kwargs:
        request.GET[key] = kwargs[key]
    response = view(request, **view_kwargs)
    _replace_dict_values(str(''), None, kwargs)
    return response, kwargs, reversal
项目:intel-manager-for-lustre    作者:intel-hpdd    | 项目源码 | 文件源码
def obj_create(self, bundle, **kwargs):
        request = bundle.request
        # NB: This is safe because we've already validated the input.
        host_id = resolve(bundle.data['host'])[2]['pk']
        filesystem_id = resolve(bundle.data['filesystem'])[2]['pk']

        # Now take a copy of the data dict and clean it up.
        clean_data = copy.deepcopy(bundle.data)
        clean_data['host'] = host_id
        clean_data['filesystem'] = filesystem_id

        copytool = JobSchedulerClient.create_copytool(clean_data)
        ct_bundle = self.full_dehydrate(self.build_bundle(obj = copytool))
        ct_data = self.alter_detail_data_to_serialize(request, ct_bundle).data

        raise custom_response(self, request, http.HttpAccepted,
                              {'copytool': ct_data})
项目:beg-django-e-commerce    作者:Apress    | 项目源码 | 文件源码
def test_view_product(self):
        """ test product view loads """
        product = Product.active.all()[0]
        product_url = product.get_absolute_url()
        url_entry = urlresolvers.resolve(product_url)
        template_name = url_entry[2]['template_name']
        response = self.client.get(product_url)
        self.failUnless(response)
        self.assertEqual(response.status_code, httplib.OK)
        self.assertTemplateUsed(response, template_name)
        self.assertContains(response, product.name)
        self.assertContains(response, html.escape(product.description))
        # check for cart form in product page response
        cart_form = response.context[0]['form']
        self.failUnless(cart_form)
        # check that the cart form is instance of correct form class
        self.failUnless(isinstance(cart_form, ProductAddToCartForm))

        product_reviews = response.context[0].get('product_reviews',None)
        self.failIfEqual(product_reviews, None)
项目:toga-django    作者:pybee    | 项目源码 | 文件源码
def materialize(self):
        children = []
        if self.source:
            api_view = resolve(reverse(self.source)).func
            for child in api_view.view_class().get_queryset():
                children.append(self.item_class(child, self.detail).materialize())
        else:
            for child in self.children:
                children.add(child.materialize())

        return TogaList(
            widget_id=self.widget_id,
            children=children,
            create_url=reverse(self.source),
            on_item_press=self.handler(self.on_item_press, 'on_item_press') if self.on_item_press else None
        )
项目:db0.company    作者:db0company    | 项目源码 | 文件源码
def globalContext(request, nav=NAV):
    rainbow = utils.getRainbowFromSize(len(nav))
    return {
        'current': resolve(request.path_info).url_name,
        'static_url': (settings.STATIC_FULL_URL + settings.STATIC_URL).replace('//static', '/static'),
        'site_name': 'db0.company',
        'site_description': 'Deby Lepage Official Website',
        'debug': settings.DEBUG,
        'static_files_version': '2',
        'rainbow': [(
            (index * (100/len(RAINBOW))),
            ((index + 1) * (100 / (len(RAINBOW)))),
            color,
        ) for index, color in enumerate(RAINBOW)],
        'nav': [tuple(list(info) + [rainbow[index]]) for index, info in enumerate(nav)],
    }
项目:WPS-4th    作者:Fastcampus-WPS    | 项目源码 | 文件源码
def test_root_url_resolves_to_index_view(self):
        # resolve???? ??? ?? URL??? ???? view??? ??? ??
        view = resolve('/')
        # ????.func? view??? ???
        self.assertEqual(view.func, index)
项目:WPS-4th    作者:Fastcampus-WPS    | 项目源码 | 文件源码
def test_root_url_resolves_to_index_view(self):
        # resolve???? ??? ?? URL??? ???? view??? ??? ??
        view = resolve('/')
        # ????.func? view??? ???
        self.assertEqual(view.func, index)
项目:WPS-4th    作者:Fastcampus-WPS    | 项目源码 | 文件源码
def test_root_url_resolves_to_index_view(self):
        # resolve???? ??? ?? URL??? ???? view??? ??? ??
        view = resolve('/')
        # ????.func? view??? ???
        self.assertEqual(view.func, index)
项目:WPS-4th    作者:Fastcampus-WPS    | 项目源码 | 文件源码
def test_root_url_resolves_to_index_view(self):
        # resolve???? ??? ?? URL??? ???? view??? ??? ??
        view = resolve('/')
        # ????.func? view??? ???
        self.assertEqual(view.func, index)
项目:WPS-4th    作者:Fastcampus-WPS    | 项目源码 | 文件源码
def test_root_url_resolves_to_index_view(self):
        # resolve???? ??? ?? URL??? ???? view??? ??? ??
        view = resolve('/')
        # ????.func? view??? ???
        self.assertEqual(view.func, index)
项目:MetaCI    作者:SalesforceFoundation    | 项目源码 | 文件源码
def test_list_resolve(self):
        """/users/ should resolve to users:list."""
        self.assertEqual(resolve('/users/').view_name, 'users:list')
项目:MetaCI    作者:SalesforceFoundation    | 项目源码 | 文件源码
def test_redirect_resolve(self):
        """/users/~redirect/ should resolve to users:redirect."""
        self.assertEqual(
            resolve('/users/~redirect/').view_name,
            'users:redirect'
        )
项目:MetaCI    作者:SalesforceFoundation    | 项目源码 | 文件源码
def test_detail_resolve(self):
        """/users/testuser/ should resolve to users:detail."""
        self.assertEqual(resolve('/users/testuser/').view_name, 'users:detail')
项目:MetaCI    作者:SalesforceFoundation    | 项目源码 | 文件源码
def test_update_resolve(self):
        """/users/~update/ should resolve to users:update."""
        self.assertEqual(
            resolve('/users/~update/').view_name,
            'users:update'
        )
项目:django-simplestore    作者:martinstastny    | 项目源码 | 文件源码
def test_products_list_resolves_to_product_list_view(self):
        """Check if ProductList URL is matching correct view."""
        product_list = resolve(self.product_list_url)
        self.assertEqual(product_list.func.__name__, ProductsListView.__name__)
项目:django-simplestore    作者:martinstastny    | 项目源码 | 文件源码
def test_product_detail_url_resolves_to_product_detail_view(self):
        """
        Check if Product Detail URL is matching the correct view.
        """
        product_detail = resolve(self.product_detail_url)
        self.assertEqual(
            product_detail.func.__name__,
            ProductDetailView.__name__
        )
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def add_preserved_filters(context, url, popup=False, to_field=None):
    opts = context.get('opts')
    preserved_filters = context.get('preserved_filters')

    parsed_url = list(urlparse(url))
    parsed_qs = dict(parse_qsl(parsed_url[4]))
    merged_qs = dict()

    if opts and preserved_filters:
        preserved_filters = dict(parse_qsl(preserved_filters))

        match_url = '/%s' % url.partition(get_script_prefix())[2]
        try:
            match = resolve(match_url)
        except Resolver404:
            pass
        else:
            current_url = '%s:%s' % (match.app_name, match.url_name)
            changelist_url = 'admin:%s_%s_changelist' % (opts.app_label, opts.model_name)
            if changelist_url == current_url and '_changelist_filters' in preserved_filters:
                preserved_filters = dict(parse_qsl(preserved_filters['_changelist_filters']))

        merged_qs.update(preserved_filters)

    if popup:
        from django.contrib.admin.options import IS_POPUP_VAR
        merged_qs[IS_POPUP_VAR] = 1
    if to_field:
        from django.contrib.admin.options import TO_FIELD_VAR
        merged_qs[TO_FIELD_VAR] = to_field

    merged_qs.update(parsed_qs)

    parsed_url[4] = urlencode(merged_qs)
    return urlunparse(parsed_url)
项目:cookiecutter-django-reactjs    作者:genomics-geek    | 项目源码 | 文件源码
def test_list_resolve(self):
        """/users/ should resolve to users:list."""
        self.assertEqual(resolve('/users/').view_name, 'users:list')
项目:cookiecutter-django-reactjs    作者:genomics-geek    | 项目源码 | 文件源码
def test_redirect_resolve(self):
        """/users/~redirect/ should resolve to users:redirect."""
        self.assertEqual(
            resolve('/users/~redirect/').view_name,
            'users:redirect'
        )
项目:cookiecutter-django-reactjs    作者:genomics-geek    | 项目源码 | 文件源码
def test_detail_resolve(self):
        """/users/testuser/ should resolve to users:detail."""
        self.assertEqual(resolve('/users/testuser/').view_name, 'users:detail')
项目:cookiecutter-django-reactjs    作者:genomics-geek    | 项目源码 | 文件源码
def test_update_resolve(self):
        """/users/~update/ should resolve to users:update."""
        self.assertEqual(
            resolve('/users/~update/').view_name,
            'users:update'
        )
项目:rovercode-web    作者:rovercode    | 项目源码 | 文件源码
def test_home_resolve(self):
        """/mission-control/ should resolve to mission-control:home."""
        self.assertEqual(
            resolve('/mission-control/').view_name,
            'mission-control:home')
项目:rovercode-web    作者:rovercode    | 项目源码 | 文件源码
def test_home_load_resolve(self):
        """/mission-control/load/1 should resolve to mission-control:home."""
        match = resolve('/mission-control/load/1/')
        self.assertEqual(match.view_name, 'mission-control:home_with_load')
        self.assertEqual(match.kwargs['bd'], '1')
项目:rovercode-web    作者:rovercode    | 项目源码 | 文件源码
def test_bd_list_resolve(self):
        """/mission-control/bd-list/ should resolve to mission-control:bd_list.""" # noqa
        self.assertEqual(
            resolve('/mission-control/bd-list/').view_name,
            'mission-control:bd_list')
项目:rovercode-web    作者:rovercode    | 项目源码 | 文件源码
def test_rover_list_resolve(self):
        """/mission-control/rover-list/ should resolve to mission-control:rover_list.""" # noqa
        self.assertEqual(
            resolve('/mission-control/rover-list/').view_name,
            'mission-control:rover_list')
项目:rovercode-web    作者:rovercode    | 项目源码 | 文件源码
def test_rovers_resolve(self):
        """/mission-control/rovers/ should resolve to mission-control:rover-list.""" # noqa
        self.assertEqual(
            resolve('/mission-control/rovers/').view_name,
            'mission-control:rover-list')
项目:rovercode-web    作者:rovercode    | 项目源码 | 文件源码
def test_rover_settings_resolve(self):
        """/mission-control/rover-settings/ should resolve to mission-control:rover_settings."""  # noqa
        self.assertEqual(
            resolve('/mission-control/rover-settings/1/').view_name,
            'mission-control:rover_settings')
项目:rovercode-web    作者:rovercode    | 项目源码 | 文件源码
def test_posts_resolve(self):
        """/blog/ should resolve to blog:post_list."""
        self.assertEqual(
            resolve('/blog/').view_name,
            'blog:post_list')
项目:rovercode-web    作者:rovercode    | 项目源码 | 文件源码
def test_drafts_list_resolve(self):
        """/blog/post-drafts-list/ should resolve to blog:post_drafts_list."""
        self.assertEqual(
            resolve('/blog/post-drafts-list/').view_name,
            'blog:post_drafts_list')
项目:rovercode-web    作者:rovercode    | 项目源码 | 文件源码
def test_post_edit_load_resolve(self):
        """/blog/post-edit/f1rst-p0st should resolve to blog:post_edit."""
        match = resolve('/blog/post-edit/f1rst-p0st/')
        self.assertEqual(match.view_name, 'blog:post_edit')
        self.assertEqual(match.kwargs['slug'], 'f1rst-p0st')
项目:rovercode-web    作者:rovercode    | 项目源码 | 文件源码
def test_post_new_load_resolve(self):
        """/blog/post-edit/ should resolve to blog:post_new."""
        match = resolve('/blog/post-edit/')
        self.assertEqual(match.view_name, 'blog:post_new')
项目:rovercode-web    作者:rovercode    | 项目源码 | 文件源码
def test_block_diagrams_resolve(self):
        """/blog/posts/ should resolve to blog:post-list."""  # noqa
        self.assertEqual(
            resolve('/blog/posts/').view_name,
            'blog:post-list')
项目:rovercode-web    作者:rovercode    | 项目源码 | 文件源码
def test_list_resolve(self):
        """/users/ should resolve to users:list."""
        self.assertEqual(resolve('/users/').view_name, 'users:list')
项目:rovercode-web    作者:rovercode    | 项目源码 | 文件源码
def test_redirect_resolve(self):
        """/users/~redirect/ should resolve to users:redirect."""
        self.assertEqual(
            resolve('/users/~redirect/').view_name,
            'users:redirect'
        )
项目:rovercode-web    作者:rovercode    | 项目源码 | 文件源码
def test_detail_resolve(self):
        """/users/testuser/ should resolve to users:detail."""
        self.assertEqual(resolve('/users/testuser/').view_name, 'users:detail')
项目:rovercode-web    作者:rovercode    | 项目源码 | 文件源码
def test_update_resolve(self):
        """/users/~update/ should resolve to users:update."""
        self.assertEqual(
            resolve('/users/~update/').view_name,
            'users:update'
        )
项目:Server    作者:malaonline    | 项目源码 | 文件源码
def menu_style_check(context, *args, **kwargs):
    request = context['request']
    active_style = 'menu_active'
    display_style = 'hidden'
    try:
        resolver_match = urlresolvers.resolve(request.path_info)
        url_name = resolver_match.url_name
        namespaces = resolver_match.namespaces
        for arg in args:
            tmp_path = '.'.join(namespaces)
            if len(tmp_path) > 0:
                tmp_path += ':' + url_name
            else:
                tmp_path = url_name
            s = arg.split(':')
            if len(s):
                temp_url_name = s[-1]
                for group in request.user.groups.all():
                    for staff_permission in group.staffpermission_set.all():
                        if staff_permission.allowed_url_name == 'all' \
                                or staff_permission.allowed_url_name == temp_url_name:
                            display_style = ''
            if tmp_path == arg:
                return active_style + ' ' + display_style
    except:
        return display_style

    return display_style
项目:dit-thumber    作者:uktrade    | 项目源码 | 文件源码
def _get_view_from_url(self, url):
        url_data = urlparse(url)
        host = url_data.netloc
        path = url_data.path
        viewname = resolve(path).view_name
        return viewname
项目:led_wall_server    作者:GWTechCollective    | 项目源码 | 文件源码
def test_list_resolve(self):
        """/users/ should resolve to users:list."""
        self.assertEqual(resolve('/users/').view_name, 'users:list')
项目:led_wall_server    作者:GWTechCollective    | 项目源码 | 文件源码
def test_redirect_resolve(self):
        """/users/~redirect/ should resolve to users:redirect."""
        self.assertEqual(
            resolve('/users/~redirect/').view_name,
            'users:redirect'
        )
项目:led_wall_server    作者:GWTechCollective    | 项目源码 | 文件源码
def test_detail_resolve(self):
        """/users/testuser/ should resolve to users:detail."""
        self.assertEqual(resolve('/users/testuser/').view_name, 'users:detail')