我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.core.urlresolvers.NoReverseMatch()。
def current_page_info(context, stylesheet=True, url_namespace=None): request = context.get('request') try: if url_namespace: switch_edit_mode_url = reverse( '{0}:switch_edit_mode'.format(url_namespace) ) else: switch_edit_mode_url = reverse('switch_edit_mode') except NoReverseMatch: switch_edit_mode_url = reverse('powerpages:switch_edit_mode') return { 'show_info': bool( request and request.session.get('WEBSITE_EDIT_MODE') ), 'page': context.get('website_page'), 'stylesheet': stylesheet, 'switch_edit_mode_url': switch_edit_mode_url, }
def get_link_url(self, datum=None): """Returns the final URL based on the value of ``url``. If ``url`` is callable it will call the function. If not, it will then try to call ``reverse`` on ``url``. Failing that, it will simply return the value of ``url`` as-is. When called for a row action, the current row data object will be passed as the first parameter. """ if not self.url: raise NotImplementedError('A LinkAction class must have a ' 'url attribute or define its own ' 'get_link_url method.') if callable(self.url): return self.url(datum, **self.kwargs) try: if datum: obj_id = self.table.get_object_id(datum) return urlresolvers.reverse(self.url, args=(obj_id,)) else: return urlresolvers.reverse(self.url) except urlresolvers.NoReverseMatch as ex: LOG.info('No reverse found for "%s": %s' % (self.url, ex)) return self.url
def get_link_url(self, datum): """Returns the final value for the column's ``link`` property. If ``allowed_data_types`` of this column is not empty and the datum has an assigned type, check if the datum's type is in the ``allowed_data_types`` list. If not, the datum won't be displayed as a link. If ``link`` is a callable, it will be passed the current data object and should return a URL. Otherwise ``get_link_url`` will attempt to call ``reverse`` on ``link`` with the object's id as a parameter. Failing that, it will simply return the value of ``link``. """ if self.allowed_data_types: data_type_name = self.table._meta.data_type_name data_type = getattr(datum, data_type_name, None) if data_type and (data_type not in self.allowed_data_types): return None obj_id = self.table.get_object_id(datum) if callable(self.link): return self.link(datum) try: return urlresolvers.reverse(self.link, args=(obj_id,)) except urlresolvers.NoReverseMatch: return self.link
def context(self, context): btns = [] for b in self.q_btns: btn = {} if 'model' in b: model = self.get_model(b['model']) if not self.user.has_perm("%s.view_%s" % (model._meta.app_label, model._meta.model_name)): continue btn['url'] = reverse("%s:%s_%s_%s" % (self.admin_site.app_name, model._meta.app_label, model._meta.model_name, b.get('view', 'changelist'))) btn['title'] = model._meta.verbose_name btn['icon'] = self.dashboard.get_model_icon(model) else: try: btn['url'] = reverse(b['url']) except NoReverseMatch: btn['url'] = b['url'] if 'title' in b: btn['title'] = b['title'] if 'icon' in b: btn['icon'] = b['icon'] btns.append(btn) context.update({'btns': btns})
def block_top_navbar(self, context, nodes): search_models = [] site_name = self.admin_site.name if self.global_search_models == None: models = self.admin_site._registry.keys() else: models = self.global_search_models for model in models: app_label = model._meta.app_label if self.has_model_perm(model, "view"): info = (app_label, model._meta.model_name) if getattr(self.admin_site._registry[model], 'search_fields', None): try: search_models.append({ 'title': _('Search %s') % capfirst(model._meta.verbose_name_plural), 'url': reverse('xadmin:%s_%s_changelist' % info, current_app=site_name), 'model': model }) except NoReverseMatch: pass return nodes.append(loader.render_to_string('xadmin/blocks/comm.top.topnav.html', {'search_models': search_models, 'search_name': SEARCH_VAR}))
def block_top_navmenu(self, context, nodes): add_models = [] site_name = self.admin_site.name if self.global_add_models == None: models = self.admin_site._registry.keys() else: models = self.global_add_models for model in models: app_label = model._meta.app_label if self.has_model_perm(model, "add"): info = (app_label, model._meta.model_name) try: add_models.append({ 'title': _('Add %s') % capfirst(model._meta.verbose_name), 'url': reverse('xadmin:%s_%s_add' % info, current_app=site_name), 'model': model }) except NoReverseMatch: pass nodes.append( loader.render_to_string('xadmin/blocks/comm.top.topnav.html', {'add_models': add_models}))
def handle_user_url(self, menu_item): """ Evaluate user defined URL :type menu_item: ChildItem or ParentItem """ if callable(menu_item.url): menu_item.url = menu_item.url(self.request, self.context) return menu_item if '/' in menu_item.url: return menu_item from django.core.urlresolvers import reverse, NoReverseMatch try: menu_item.url = reverse(menu_item.url, current_app=self.current_app) menu_item._url_name = menu_item.url except NoReverseMatch: menu_item.url = '#no-reverse-match' return menu_item
def _reverse(self, viewname, args, kwargs, current_app=None, fail=True): from django.core.urlresolvers import reverse, NoReverseMatch # Try to look up the URL twice: once given the view name, # and again relative to what we guess is the "main" app. url = '' urlconf=kwargs.pop('urlconf', None) try: url = reverse(viewname, urlconf=urlconf, args=args, kwargs=kwargs, current_app=current_app) except NoReverseMatch as ex: projectname = settings.SETTINGS_MODULE.split('.')[0] try: url = reverse(projectname + '.' + viewname, urlconf=urlconf, args=args, kwargs=kwargs) except NoReverseMatch: if fail: raise ex else: return '' return url
def handle_redirect_to_login(request, **kwargs): login_url = kwargs.get("login_url") redirect_field_name = kwargs.get("redirect_field_name") next_url = kwargs.get("next_url") if login_url is None: login_url = settings.ACCOUNT_LOGIN_URL if next_url is None: next_url = request.get_full_path() try: login_url = urlresolvers.reverse(login_url) except urlresolvers.NoReverseMatch: if callable(login_url): raise if "/" not in login_url and "." not in login_url: raise url_bits = list(urlparse.urlparse(login_url)) if redirect_field_name: querystring = QueryDict(url_bits[4], mutable=True) querystring[redirect_field_name] = next_url url_bits[4] = querystring.urlencode(safe="/") return HttpResponseRedirect(urlparse.urlunparse(url_bits))
def handle_redirect_to_login(request, **kwargs): login_url = kwargs.get("login_url") redirect_field_name = kwargs.get("redirect_field_name") next_url = kwargs.get("next_url") if login_url is None: login_url = settings.ACCOUNT_LOGIN_URL if next_url is None: next_url = request.get_full_path() try: login_url = urlresolvers.reverse(login_url) except urlresolvers.NoReverseMatch: if callable(login_url): raise if "/" not in login_url and "." not in login_url: raise url_bits = list(urlparse(login_url)) if redirect_field_name: querystring = QueryDict(url_bits[4], mutable=True) querystring[redirect_field_name] = next_url url_bits[4] = querystring.urlencode(safe="/") return HttpResponseRedirect(urlunparse(url_bits))
def check_link(self, instance, verify_exists=False): internal_link = instance.internal_link valid = False if internal_link: try: url = internal_link.get_absolute_url(instance.language) except NoReverseMatch: url = None else: valid = True else: url = instance.external_link valid = self.validate_url(url, verify_exists=verify_exists) return LinkReport( valid=valid, text=instance.name, url=url, )
def menu_active(context, pattern_or_urlname): try: # handle slash if reverse(pattern_or_urlname) == '/': pattern = '^/$' else: pattern = '^' + reverse(pattern_or_urlname) + "([-\w]+)?" except NoReverseMatch: pattern = pattern_or_urlname if context.get('request'): path = context.get('request').path if re.search(pattern, path): return 'selected' return ''
def __init__(self, title, url, attrs=None, item_id=''): super().__init__() self._parent = None self._item_id = item_id self._title = str(title) try: self._url = resolve_url(url) except NoReverseMatch: self._url = url if attrs is None: self._classes = '' self._attrs = '' else: self._classes = attrs.pop('class', '') self._attrs = flatatt(attrs)
def optional_logout(request, user): """ Include a logout snippet if REST framework's logout view is in the URLconf. """ try: logout_url = reverse('rest_framework:logout') except NoReverseMatch: snippet = format_html('<li class="navbar-text">{user}</li>', user=escape(user)) return mark_safe(snippet) snippet = """<li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> {user} <b class="caret"></b> </a> <ul class="dropdown-menu"> <li><a href='{href}?next={next}'>Log out</a></li> </ul> </li>""" snippet = format_html(snippet, user=escape(user), href=logout_url, next=escape(request.path)) return mark_safe(snippet)
def reverse(viewname, args=None, kwargs=None, request=None, format=None, **extra): """ If versioning is being used then we pass any `reverse` calls through to the versioning scheme instance, so that the resulting URL can be modified if needed. """ scheme = getattr(request, 'versioning_scheme', None) if scheme is not None: try: url = scheme.reverse(viewname, args, kwargs, request, format, **extra) except NoReverseMatch: # In case the versioning scheme reversal fails, fallback to the # default implementation url = _reverse(viewname, args, kwargs, request, format, **extra) else: url = _reverse(viewname, args, kwargs, request, format, **extra) return preserve_builtin_query_params(url, request)
def _get_hook_url(self, draft, channel_type, hook_name): draft_field = "{}_done".format(hook_name) # hook has already been called if draft_field in draft and draft[draft_field]: return None # hook has not been called or is not finished else: channel_id = draft["{}_channel_id".format(channel_type)] channel = Channel.objects.get(id=channel_id) channel_name = channel.name.lower() try: hook_url = reverse("{}:{}".format(channel_name, hook_name)) except NoReverseMatch: draft[draft_field] = True return None draft[draft_field] = False return hook_url
def test__get_hook_url__no_hook(self, mock_channel_get, mock_reverse): view = RecipeCreateBaseView() draft = {"trigger_channel_id": 42} channel_type = "trigger" hook_name = "the_hook" mock_channel_get.return_value = MagicMock() mock_channel_get.return_value.name = "Channel" mock_reverse.side_effect = NoReverseMatch() hook_url = view._get_hook_url(draft, channel_type, hook_name) mock_channel_get.assert_called_with(id=42) mock_reverse.assert_called_with("channel:the_hook") self.assertTrue(draft['the_hook_done']) self.assertIsNone(hook_url)
def fetch_captcha_store(self, name, value, attrs=None): """ Fetches a new CaptchaStore This has to be called inside render """ try: reverse('captcha-image', args=('dummy',)) except NoReverseMatch: raise ImproperlyConfigured('Make sure you\'ve included captcha.urls as explained in the INSTALLATION section on http://readthedocs.org/docs/django-simple-captcha/en/latest/usage.html#installation') key = CaptchaStore.generate_key() # these can be used by format_output and render self._value = [key, u('')] self._key = key self.id_ = self.build_attrs(attrs).get('id', None)
def reverse(viewname, args=None, kwargs=None, request=None, format=None, **extra): """ If versioning is being used then we pass any `reverse` calls through to the versioning scheme instance, so that the resulting URL can be modified if needed. """ scheme = getattr(request, 'versioning_scheme', None) if scheme is not None: try: return scheme.reverse(viewname, args, kwargs, request, format, **extra) except NoReverseMatch: # In case the versioning scheme reversal fails, fallback to the default implementation pass return _reverse(viewname, args, kwargs, request, format, **extra)
def context(self, context): btns = [] for b in self.q_btns: btn = {} if 'model' in b: model = self.get_model(b['model']) if not self.user.has_perm("%s.view_%s" % (model._meta.app_label, model._meta.module_name)): continue btn['url'] = reverse("%s:%s_%s_%s" % (self.admin_site.app_name, model._meta.app_label, model._meta.module_name, b.get('view', 'changelist'))) btn['title'] = model._meta.verbose_name btn['icon'] = self.dashboard.get_model_icon(model) else: try: btn['url'] = reverse(b['url']) except NoReverseMatch: btn['url'] = b['url'] if 'title' in b: btn['title'] = b['title'] if 'icon' in b: btn['icon'] = b['icon'] btns.append(btn) context.update({'btns': btns})
def block_top_navbar(self, context, nodes): search_models = [] site_name = self.admin_site.name if self.global_search_models == None: models = self.admin_site._registry.keys() else: models = self.global_search_models for model in models: app_label = model._meta.app_label if self.has_model_perm(model, "view"): info = (app_label, model._meta.module_name) if getattr(self.admin_site._registry[model], 'search_fields', None): try: search_models.append({ 'title': _('Search %s') % capfirst(model._meta.verbose_name_plural), 'url': reverse('xadmin:%s_%s_changelist' % info, current_app=site_name), 'model': model }) except NoReverseMatch: pass nodes.append(loader.render_to_string('xadmin/blocks/comm.top.topnav.html', {'search_models': search_models, 'search_name': SEARCH_VAR}))
def block_top_navmenu(self, context, nodes): add_models = [] site_name = self.admin_site.name if self.global_add_models == None: models = self.admin_site._registry.keys() else: models = self.global_add_models for model in models: app_label = model._meta.app_label if self.has_model_perm(model, "add"): info = (app_label, model._meta.module_name) try: add_models.append({ 'title': _('Add %s') % capfirst(model._meta.verbose_name), 'url': reverse('xadmin:%s_%s_add' % info, current_app=site_name), 'model': model }) except NoReverseMatch: pass nodes.append( loader.render_to_string('xadmin/blocks/comm.top.topnav.html', {'add_models': add_models}))
def get_block_type_queryset(self,db): qry = None for m in self.get_block_models(): try: admin_url(m, 'add') except NoReverseMatch: continue q = models.Q(app_label=m._meta.app_label) & \ models.Q(model=m._meta.object_name.lower()) qry = qry | q if qry else q # If qry has not been set, i.e. no blocks extend the block_type, or # Blocks do not have an admin, then exclude all content types.. return ContentType.objects.filter(qry).using(db) if qry else \ ContentType.objects.exclude(pk__gte=0)
def who(self, comment): """ Who made this comment. If it is a user, link to their profile in the admin; otherwise show their name and email address. """ if comment.user: user = comment.user user_display = user.get_full_name() \ or getattr(user, user.USERNAME_FIELD) try: # Just incase someone is running a minimal install without # wagtailusers installed. return format_html('<a href="{url}">{name}</a>'.format( url=reverse('wagtailusers_users:edit', args=[user.pk]), name=user_display)) except NoReverseMatch: return user_display else: return '{name} ({email})'.format(name=comment.user_name, email=comment.user_email)
def done(self, form_list, **kwargs): """ This step only runs if all forms are valid. Simply emits a simple template that uses JS to redirect to the newly created object. """ form_two = list(form_list)[1] instance = form_two.save() url = self.get_success_url(instance) if not url: page = self.get_origin_page() if page: try: url = page.get_absolute_url(self.language_code) except NoReverseMatch: url = '/' else: url = '/' return SimpleTemplateResponse("cms/wizards/done.html", {"url": url})
def get_breadcrumb(self): from cms.models import Page model = self.placeholder._get_attached_model() or Page breadcrumb = [] for parent in self.get_ancestors(): try: url = force_text( admin_reverse("%s_%s_edit_plugin" % (model._meta.app_label, model._meta.model_name), args=[parent.pk])) except NoReverseMatch: url = force_text( admin_reverse("%s_%s_edit_plugin" % (Page._meta.app_label, Page._meta.model_name), args=[parent.pk])) breadcrumb.append({'title': force_text(parent.get_plugin_name()), 'url': url}) try: url = force_text( admin_reverse("%s_%s_edit_plugin" % (model._meta.app_label, model._meta.model_name), args=[self.pk])) except NoReverseMatch: url = force_text( admin_reverse("%s_%s_edit_plugin" % (Page._meta.app_label, Page._meta.model_name), args=[self.pk])) breadcrumb.append({'title': force_text(self.get_plugin_name()), 'url': url}) return breadcrumb
def get_nodes(self, request): nodes = [] for cat in Category.objects.all(): n = NavigationNode(cat.name, cat.get_absolute_url(), cat.pk, cat.parent_id, "sampleapp") nodes.append(n) try: n = NavigationNode(_('sample root page'), reverse('sample-root'), 1) n2 = NavigationNode(_('sample settings page'), reverse('sample-settings'), 2) n3 = NavigationNode(_('sample account page'), reverse('sample-account'), 3) n4 = NavigationNode(_('sample my profile page'), reverse('sample-profile'), 4, 3) nodes.append(n) nodes.append(n2) nodes.append(n3) nodes.append(n4) except NoReverseMatch: pass return nodes