我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.core.urlresolvers.resolve()。
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
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
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
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
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
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) )
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]))
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
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})
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)
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 )
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)], }
def test_root_url_resolves_to_index_view(self): # resolve???? ??? ?? URL??? ???? view??? ??? ?? view = resolve('/') # ????.func? view??? ??? self.assertEqual(view.func, index)
def test_list_resolve(self): """/users/ should resolve to users:list.""" self.assertEqual(resolve('/users/').view_name, 'users:list')
def test_redirect_resolve(self): """/users/~redirect/ should resolve to users:redirect.""" self.assertEqual( resolve('/users/~redirect/').view_name, 'users:redirect' )
def test_detail_resolve(self): """/users/testuser/ should resolve to users:detail.""" self.assertEqual(resolve('/users/testuser/').view_name, 'users:detail')
def test_update_resolve(self): """/users/~update/ should resolve to users:update.""" self.assertEqual( resolve('/users/~update/').view_name, 'users:update' )
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__)
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__ )
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)
def test_home_resolve(self): """/mission-control/ should resolve to mission-control:home.""" self.assertEqual( resolve('/mission-control/').view_name, 'mission-control:home')
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')
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')
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')
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')
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')
def test_posts_resolve(self): """/blog/ should resolve to blog:post_list.""" self.assertEqual( resolve('/blog/').view_name, 'blog:post_list')
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')
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')
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')
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')
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
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