Python django.core.urlresolvers.NoReverseMatch() Examples

The following are 30 code examples for showing how to use django.core.urlresolvers.NoReverseMatch(). 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.core.urlresolvers , or try the search function .

Example 1
Project: StormOnline   Author: stormsha   File: dashboard.py    License: Apache License 2.0 6 votes vote down vote up
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}) 
Example 2
Project: StormOnline   Author: stormsha   File: topnav.py    License: Apache License 2.0 6 votes vote down vote up
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})) 
Example 3
Project: StormOnline   Author: stormsha   File: topnav.py    License: Apache License 2.0 6 votes vote down vote up
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})) 
Example 4
Project: GTDWeb   Author: lanbing510   File: base.py    License: GNU General Public License v2.0 6 votes vote down vote up
def get_redirect_url(self, *args, **kwargs):
        """
        Return the URL redirect to. Keyword arguments from the
        URL pattern match generating the redirect request
        are provided as kwargs to this method.
        """
        if self.url:
            url = self.url % kwargs
        elif self.pattern_name:
            try:
                url = reverse(self.pattern_name, args=args, kwargs=kwargs)
            except NoReverseMatch:
                return None
        else:
            return None

        args = self.request.META.get('QUERY_STRING', '')
        if args and self.query_string:
            url = "%s?%s" % (url, args)
        return url 
Example 5
Project: DCRM   Author: 82Flex   File: menu.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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 
Example 6
Project: osler   Author: SaturdayNeighborhoodHealthClinic   File: tests.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_followup_view_rendering(self):
        from django.core.urlresolvers import NoReverseMatch

        for url in urls.urlpatterns:
            if url.name in ['new-followup', 'followup']:
                continue

            # all the URLs have either one parameter or none. Try one
            # parameter first; if that fails, try with none.
            try:
                self.verify_rendering(url.name, (1,))
            except NoReverseMatch:
                self.verify_rendering(url.name)

        for fu_type in FU_TYPES:
            self.verify_rendering('new-followup', (1, fu_type))

        # TODO: build in checks for 'followup' once the objects exist.
        # for model in ['General', 'Lab']:
        #     self.verify_rendering('followup',
        #                           kwargs={"pk": 1, "model": model}) 
Example 7
Project: django-leonardo   Author: django-leonardo   File: leonardo_tags.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def render(self, context):
        args = [arg.resolve(context) for arg in self.args]
        kwargs = dict([
            (smart_str(k, 'ascii'), v.resolve(context))
            for k, v in self.kwargs.items()])
        view_name = self.view_name.resolve(context)
        urlconf = self.urlconf.resolve(context)

        try:
            url = do_app_reverse(
                view_name, urlconf, args=args, kwargs=kwargs,
                current_app=context.current_app)
        except NoReverseMatch:
            if self.asvar is None:
                raise
            url = ''

        if self.asvar:
            context[self.asvar] = url
            return ''
        else:
            return url 
Example 8
Project: openhgsenti   Author: drexly   File: base.py    License: Apache License 2.0 6 votes vote down vote up
def get_redirect_url(self, *args, **kwargs):
        """
        Return the URL redirect to. Keyword arguments from the
        URL pattern match generating the redirect request
        are provided as kwargs to this method.
        """
        if self.url:
            url = self.url % kwargs
        elif self.pattern_name:
            try:
                url = reverse(self.pattern_name, args=args, kwargs=kwargs)
            except NoReverseMatch:
                return None
        else:
            return None

        args = self.request.META.get('QUERY_STRING', '')
        if args and self.query_string:
            url = "%s?%s" % (url, args)
        return url 
Example 9
Project: imoocc   Author: iopsgroup   File: dashboard.py    License: GNU General Public License v2.0 6 votes vote down vote up
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}) 
Example 10
Project: imoocc   Author: iopsgroup   File: topnav.py    License: GNU General Public License v2.0 6 votes vote down vote up
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})) 
Example 11
Project: imoocc   Author: iopsgroup   File: topnav.py    License: GNU General Public License v2.0 6 votes vote down vote up
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})) 
Example 12
Project: devops   Author: madre   File: dashboard.py    License: MIT License 6 votes vote down vote up
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}) 
Example 13
Project: devops   Author: madre   File: topnav.py    License: MIT License 6 votes vote down vote up
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

        nodes.append(loader.render_to_string('xadmin/blocks/comm.top.topnav.html', {'search_models': search_models, 'search_name': SEARCH_VAR})) 
Example 14
Project: devops   Author: madre   File: topnav.py    License: MIT License 6 votes vote down vote up
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})) 
Example 15
Project: devops   Author: madre   File: utils.py    License: MIT License 6 votes vote down vote up
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)) 
Example 16
Project: ImitationTmall_Django   Author: Liweimin0512   File: dashboard.py    License: GNU General Public License v3.0 6 votes vote down vote up
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}) 
Example 17
Project: ImitationTmall_Django   Author: Liweimin0512   File: topnav.py    License: GNU General Public License v3.0 6 votes vote down vote up
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})) 
Example 18
Project: ImitationTmall_Django   Author: Liweimin0512   File: topnav.py    License: GNU General Public License v3.0 6 votes vote down vote up
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})) 
Example 19
Project: esdc-ce   Author: erigones   File: reverse.py    License: Apache License 2.0 6 votes vote down vote up
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) 
Example 20
Project: avos   Author: CiscoSystems   File: actions.py    License: Apache License 2.0 6 votes vote down vote up
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 
Example 21
Project: avos   Author: CiscoSystems   File: base.py    License: Apache License 2.0 6 votes vote down vote up
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 
Example 22
Project: django-active-link   Author: valerymelou   File: active_link_tags.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def active_link(context, viewnames, css_class=None, strict=None, *args, **kwargs):
    """
    Renders the given CSS class if the request path matches the path of the view.
    :param context: The context where the tag was called. Used to access the request object.
    :param viewnames: The name of the view or views separated by || (include namespaces if any).
    :param css_class: The CSS class to render.
    :param strict: If True, the tag will perform an exact match with the request path.
    :return:
    """
    if css_class is None:
        css_class = getattr(settings, 'ACTIVE_LINK_CSS_CLASS', 'active')

    if strict is None:
        strict = getattr(settings, 'ACTIVE_LINK_STRICT', False)

    request = context.get('request')
    if request is None:
        # Can't work without the request object.
        return ''
    active = False
    views = viewnames.split('||')
    for viewname in views:
        try:
            path = reverse(viewname.strip(), args=args, kwargs=kwargs)
        except NoReverseMatch:
            continue
        request_path = escape_uri_path(request.path)
        if strict:
            active = request_path == path
        else:
            active = request_path.find(path) == 0
        if active:
            break

    if active:
        return css_class

    return '' 
Example 23
Project: GTDWeb   Author: lanbing510   File: shortcuts.py    License: GNU General Public License v2.0 5 votes vote down vote up
def resolve_url(to, *args, **kwargs):
    """
    Return a URL appropriate for the arguments passed.

    The arguments could be:

        * A model: the model's `get_absolute_url()` function will be called.

        * A view name, possibly with arguments: `urlresolvers.reverse()` will
          be used to reverse-resolve the name.

        * A URL, which will be returned as-is.

    """
    # If it's a model, use get_absolute_url()
    if hasattr(to, 'get_absolute_url'):
        return to.get_absolute_url()

    if isinstance(to, Promise):
        # Expand the lazy instance, as it can cause issues when it is passed
        # further to some Python functions like urlparse.
        to = force_text(to)

    if isinstance(to, six.string_types):
        # Handle relative URLs
        if any(to.startswith(path) for path in ('./', '../')):
            return to

    # Next try a reverse URL resolution.
    try:
        return urlresolvers.reverse(to, args=args, kwargs=kwargs)
    except urlresolvers.NoReverseMatch:
        # If this is a callable, re-raise.
        if callable(to):
            raise
        # If this doesn't "feel" like a URL, re-raise.
        if '/' not in to and '.' not in to:
            raise

    # Finally, fall back and assume it's a URL
    return to 
Example 24
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: GNU General Public License v2.0 5 votes vote down vote up
def ping_google(sitemap_url=None, ping_url=PING_URL):
    """
    Alerts Google that the sitemap for the current site has been updated.
    If sitemap_url is provided, it should be an absolute path to the sitemap
    for this site -- e.g., '/sitemap.xml'. If sitemap_url is not provided, this
    function will attempt to deduce it by using urlresolvers.reverse().
    """
    if sitemap_url is None:
        try:
            # First, try to get the "index" sitemap URL.
            sitemap_url = urlresolvers.reverse('django.contrib.sitemaps.views.index')
        except urlresolvers.NoReverseMatch:
            try:
                # Next, try for the "global" sitemap URL.
                sitemap_url = urlresolvers.reverse('django.contrib.sitemaps.views.sitemap')
            except urlresolvers.NoReverseMatch:
                pass

    if sitemap_url is None:
        raise SitemapNotFound("You didn't provide a sitemap_url, and the sitemap URL couldn't be auto-detected.")

    if not django_apps.is_installed('django.contrib.sites'):
        raise ImproperlyConfigured("ping_google requires django.contrib.sites, which isn't installed.")
    Site = django_apps.get_model('sites.Site')
    current_site = Site.objects.get_current()
    url = "http://%s%s" % (current_site.domain, sitemap_url)
    params = urlencode({'sitemap': url})
    urlopen("%s?%s" % (ping_url, params)) 
Example 25
Project: django-actions-logger   Author: shtalinberg   File: models.py    License: MIT License 5 votes vote down vote up
def get_admin_url(self):
        """
        Returns the admin URL to edit the object represented by this log entry.
        """
        if self.content_type and self.object_id:
            url_name = 'admin:%s_%s_change' % (
                self.content_type.app_label,
                self.content_type.model
            )
            try:
                return reverse(url_name, args=(quote(self.object_id),))
            except NoReverseMatch:
                pass
        return None 
Example 26
Project: django-sitemessage   Author: idlesign   File: base.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _get_url(cls, name: str, message_model: Message, dispatch_model: Optional[Dispatch]) -> str:
        """Returns a common pattern sitemessage URL.

        :param name: URL name
        :param message_model:
        :param dispatch_model:

        """
        global APP_URLS_ATTACHED

        url = ''

        if dispatch_model is None:
            return url

        if APP_URLS_ATTACHED != False:  # sic!

            hashed = cls.get_dispatch_hash(dispatch_model.id, message_model.id)

            try:
                url = reverse(name, args=[message_model.id, dispatch_model.id, hashed])
                url = '%s%s' % (get_site_url(), url)
            except NoReverseMatch:
                if APP_URLS_ATTACHED is None:
                    APP_URLS_ATTACHED = False

        return url 
Example 27
Project: django-compat   Author: arteria   File: test_compat.py    License: MIT License 5 votes vote down vote up
def test_resolve_url__non_view_callable_raises_no_reverse_match(self):
        """
        Tests that passing a non-view callable into ``resolve_url`` raises a
        ``NoReverseMatch`` exception.
        """
        with self.assertRaises(NoReverseMatch):
            resolve_url(lambda: 'asdf') 
Example 28
Project: django-seo   Author: whyflyru   File: tests.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_useful_error_messages(self):
        """ Tests that the system gracefully handles a developer error
            (eg exception in get_absolute_url).
        """
        if django.VERSION < (2, 0):
            from django.core.urlresolvers import NoReverseMatch
        else:
            from django.urls import NoReverseMatch
        with self.assertRaises(NoReverseMatch):
            self.page.type = "a type with spaces!"  # this causes get_absolute_url() to fail
            self.page.save()
            self.fail("No exception raised on developer error.") 
Example 29
Project: prospector   Author: chaoss   File: renderers.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_paths_for_project(project_id):
        paths = set()

        proj_views = [
            ('hmeter_frontend:project:' + urlpat.name,
             normalize(urlpat.regex.pattern))
            for urlpat in project_urlpatterns
        ]

        # paths.add(proj.get_absolute_url())
        default_kwargs = {'id': project_id,
                          'pk': project_id,
                          'domain': ''}
        hldomain = ''

        for name, possibilities in proj_views:
            for _, keys in possibilities:
                kwargs = filterdict(default_kwargs, whitelist=keys)

                try:
                    paths.add(reverse(name, kwargs=kwargs))
                except NoReverseMatch:
                    pass

                # Also request one for hldomain if domain is a keyword here
                if 'domain' in keys:
                    kwargs['domain'] = hldomain
                    try:
                        paths.add(reverse(name, kwargs=kwargs))
                    except NoReverseMatch:
                        pass

        return paths 
Example 30
Project: django-db-mailer   Author: LPgenerator   File: mail.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _get_msg_with_track(self):
        message = self._message
        if defaults.TRACK_ENABLE is False:
            return message
        if ENABLE_LOGGING and self._template.enable_log:
            try:
                domain = Site.objects.get_current().domain
                encrypted = signing.dumps(self._log_id, compress=True)
                path = reverse('db-mail-tracker', args=[encrypted])
                message += defaults.TRACK_HTML % {
                    'url': 'http://%s%s' % (domain, path)}
            except (Site.DoesNotExist, NoReverseMatch):
                pass
        return message