Python django.urls.NoReverseMatch() Examples

The following are 30 code examples of django.urls.NoReverseMatch(). 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 also want to check out all available functions/classes of the module django.urls , or try the search function .
Example #1
Source File: tests.py    From Spirit with MIT License 6 votes vote down vote up
def test_admin_login(self):
        """
        Redirect to regular user login (optional)
        make sure you added:
        admin.site.login = login_required(admin.site.login)
        to urls.py (the one in your project's root)
        """
        # TODO: document that devs should be doing this.
        try:
            url = reverse('admin:login')
        except NoReverseMatch:
            return

        response = self.client.get(url)
        expected_url = reverse("spirit:user:auth:login") + "?next=" + reverse('admin:login')
        self.assertRedirects(response, expected_url, status_code=302) 
Example #2
Source File: reverse.py    From Dailyfresh-B2C with 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:
            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) 
Example #3
Source File: routers.py    From Dailyfresh-B2C with Apache License 2.0 6 votes vote down vote up
def get(self, request, *args, **kwargs):
        # Return a plain {"name": "hyperlink"} response.
        ret = OrderedDict()
        namespace = request.resolver_match.namespace
        for key, url_name in self.api_root_dict.items():
            if namespace:
                url_name = namespace + ':' + url_name
            try:
                ret[key] = reverse(
                    url_name,
                    args=args,
                    kwargs=kwargs,
                    request=request,
                    format=kwargs.get('format', None)
                )
            except NoReverseMatch:
                # Don't bail out if eg. no list routes exist, only detail routes.
                continue

        return Response(ret) 
Example #4
Source File: views.py    From product-definition-center with MIT License 6 votes vote down vote up
def get_url_with_resource(request):
    api_root_dict = OrderedDict()
    viewsets = {}
    ret = OrderedDict()
    list_name = router.routes[0].name
    for prefix, viewset, basename in router.registry:
        api_root_dict[prefix] = list_name.format(basename=basename)
        viewsets[prefix] = viewset
    sorted_api_root_dict = OrderedDict(sorted(api_root_dict.items()))
    for key, url_name in sorted_api_root_dict.items():
        name = URL_ARG_RE.sub(r'{\1}', key)
        ret[name] = None
        urlargs = [_get_arg_value(arg[0]) for arg in URL_ARG_RE.findall(key)]
        for getter in [_get_list_url, _get_nested_list_url, _get_detail_url]:
            try:
                if getter == _get_list_url:
                    ret[name] = urldecode(getter(url_name, viewsets[key], request))
                else:
                    ret[name] = urldecode(getter(url_name, viewsets[key], request, urlargs))
                break
            except NoReverseMatch:
                continue
    return ret 
Example #5
Source File: __init__.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
def _get_sitemap_full_url(sitemap_url):
    if not django_apps.is_installed('django.contrib.sites'):
        raise ImproperlyConfigured("ping_google requires django.contrib.sites, which isn't installed.")

    if sitemap_url is None:
        try:
            # First, try to get the "index" sitemap URL.
            sitemap_url = reverse('django.contrib.sitemaps.views.index')
        except NoReverseMatch:
            try:
                # Next, try for the "global" sitemap URL.
                sitemap_url = reverse('django.contrib.sitemaps.views.sitemap')
            except 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.")

    Site = django_apps.get_model('sites.Site')
    current_site = Site.objects.get_current()
    return 'http://%s%s' % (current_site.domain, sitemap_url) 
Example #6
Source File: registry.py    From django-ra-erp with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_model_doc_type_map(model_name):
    return model_doc_type_map.get(model_name, {'plus_list': [], 'minus_list': []})

#
# def get_model_settings():
#     if not models_settings:
#         _fill_models_settings()
#     return models_settings
#
#
# def _fill_models_settings():
#     ra_models = [] # list(get_ra_models())
#     for model in ra_models:
#         try:
#             url = model.get_redirect_url_prefix()
#         except NoReverseMatch:
#             url = ''
#
#         models_settings[model.__name__.lower()] = {'model': model, 'redirect_url_prefix': url} 
Example #7
Source File: rest_framework.py    From Dailyfresh-B2C with Apache License 2.0 6 votes vote down vote up
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) 
Example #8
Source File: renderers.py    From product-definition-center with MIT License 6 votes vote down vote up
def substitute_urls(self, view, method, text):
        def replace_url(match):
            type = match.groupdict()['type']
            parts = match.groupdict()['details'].split(':')
            url_name = parts[0]
            args = parts[1:]
            if type == 'LINK':
                args = ['{%s}' % arg for arg in args]
            try:
                if type == 'LINK':
                    url = reverse(url_name, args=args)
                    return '[`%s`](%s)' % (urldecode(url), url)
                return reverse(url_name, args=args, request=self.request)
            except NoReverseMatch:
                logger = logging.getLogger(__name__)
                logger.error('Bad URL specifier <%s> in %s.%s'
                             % (match.group(0), view.__class__.__name__, method),
                             exc_info=sys.exc_info())
                return 'BAD URL'
        return URL_SPEC_RE.sub(replace_url, text) 
Example #9
Source File: base.py    From python with 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 #10
Source File: tests_urls.py    From django-userena-ce with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_resolve_email_with_plus_url(self):
        username = "foo+bar@example.com"
        test_urls = [
            "userena_signup_complete",
            "userena_email_change",
            "userena_email_change_complete",
            "userena_email_confirm_complete",
            "userena_disabled",
            "userena_password_change",
            "userena_password_change_complete",
            "userena_profile_edit",
            "userena_profile_detail",
        ]
        for url_name in test_urls:
            try:
                reverse(url_name, kwargs={"username": username})
            except NoReverseMatch as ex:
                self.failed(ex) 
Example #11
Source File: __init__.py    From bioforum with MIT License 6 votes vote down vote up
def _get_sitemap_full_url(sitemap_url):
    if not django_apps.is_installed('django.contrib.sites'):
        raise ImproperlyConfigured("ping_google requires django.contrib.sites, which isn't installed.")

    if sitemap_url is None:
        try:
            # First, try to get the "index" sitemap URL.
            sitemap_url = reverse('django.contrib.sitemaps.views.index')
        except NoReverseMatch:
            try:
                # Next, try for the "global" sitemap URL.
                sitemap_url = reverse('django.contrib.sitemaps.views.sitemap')
            except 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.")

    Site = django_apps.get_model('sites.Site')
    current_site = Site.objects.get_current()
    return 'http://%s%s' % (current_site.domain, sitemap_url) 
Example #12
Source File: __init__.py    From python2017 with MIT License 6 votes vote down vote up
def _get_sitemap_full_url(sitemap_url):
    if not django_apps.is_installed('django.contrib.sites'):
        raise ImproperlyConfigured("ping_google requires django.contrib.sites, which isn't installed.")

    if sitemap_url is None:
        try:
            # First, try to get the "index" sitemap URL.
            sitemap_url = reverse('django.contrib.sitemaps.views.index')
        except NoReverseMatch:
            try:
                # Next, try for the "global" sitemap URL.
                sitemap_url = reverse('django.contrib.sitemaps.views.sitemap')
            except 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.")

    Site = django_apps.get_model('sites.Site')
    current_site = Site.objects.get_current()
    return 'http://%s%s' % (current_site.domain, sitemap_url) 
Example #13
Source File: __init__.py    From python with Apache License 2.0 6 votes vote down vote up
def _get_sitemap_full_url(sitemap_url):
    if not django_apps.is_installed('django.contrib.sites'):
        raise ImproperlyConfigured("ping_google requires django.contrib.sites, which isn't installed.")

    if sitemap_url is None:
        try:
            # First, try to get the "index" sitemap URL.
            sitemap_url = reverse('django.contrib.sitemaps.views.index')
        except NoReverseMatch:
            try:
                # Next, try for the "global" sitemap URL.
                sitemap_url = reverse('django.contrib.sitemaps.views.sitemap')
            except 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.")

    Site = django_apps.get_model('sites.Site')
    current_site = Site.objects.get_current()
    return 'http://%s%s' % (current_site.domain, sitemap_url) 
Example #14
Source File: base.py    From python2017 with MIT License 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 #15
Source File: test_views.py    From edx-proctoring with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_no_anonymous_access(self):
        """
        Make sure we cannot access any API methods without being logged in
        """
        self.client = Client()  # use AnonymousUser on the API calls
        for urlpattern in urlpatterns:
            if hasattr(urlpattern, 'name') and 'anonymous.' not in urlpattern.name:
                name = 'edx_proctoring:%s' % urlpattern.name
                try:
                    response = self.client.get(reverse(name))
                except NoReverseMatch:
                    # some of our URL mappings may require a argument substitution
                    try:
                        response = self.client.get(reverse(name, args=[0]))
                    except NoReverseMatch:
                        try:
                            response = self.client.get(reverse(name, args=["0/0/0"]))
                        except NoReverseMatch:
                            # some require 2 args.
                            response = self.client.get(reverse(name, args=["0/0/0", 0]))

                self.assertEqual(response.status_code, 403) 
Example #16
Source File: api.py    From edx-proctoring with GNU Affero General Public License v3.0 6 votes vote down vote up
def _resolve_prerequisite_links(exam, prerequisites):
    """
    This will inject a jumpto URL into the list of prerequisites so that a user
    can click through
    """

    for prerequisite in prerequisites:
        jumpto_url = None
        if prerequisite['namespace'] in JUMPTO_SUPPORTED_NAMESPACES and prerequisite['name']:
            try:
                jumpto_url = reverse('jump_to', args=[exam['course_id'], prerequisite['name']])
            except NoReverseMatch:
                log.exception(u"Can't find jumpto url for course %s", exam['course_id'])

        prerequisite['jumpto_url'] = jumpto_url

    return prerequisites 
Example #17
Source File: models.py    From Django-2-Web-Development-Cookbook-Third-Edition with MIT License 5 votes vote down vote up
def get_url_path(self):
        try:
            return reverse("product_detail",
                           kwargs={"slug": self.slug})
        except NoReverseMatch:
            return "" 
Example #18
Source File: models.py    From Django-2-Web-Development-Cookbook-Third-Edition with MIT License 5 votes vote down vote up
def get_url_path(self):
        try:
            return reverse("quote_detail", kwargs={"pk": self.pk})
        except NoReverseMatch:
            return "" 
Example #19
Source File: models.py    From Django-2-Web-Development-Cookbook-Third-Edition with MIT License 5 votes vote down vote up
def get_url_path(self):
        try:
            return reverse("idea_detail", kwargs={"id": self.pk})
        except NoReverseMatch:
            return "" 
Example #20
Source File: models.py    From Django-2-Web-Development-Cookbook-Third-Edition with MIT License 5 votes vote down vote up
def get_url_path(self):
        try:
            return reverse("product_detail",
                           kwargs={"slug": self.slug})
        except NoReverseMatch:
            return "" 
Example #21
Source File: models.py    From Django-2-Web-Development-Cookbook-Third-Edition with MIT License 5 votes vote down vote up
def get_url_path(self):
        try:
            return reverse("idea_detail", kwargs={"id": self.pk})
        except NoReverseMatch:
            return "" 
Example #22
Source File: models.py    From Django-2-Web-Development-Cookbook-Third-Edition with MIT License 5 votes vote down vote up
def get_url_path(self):
        try:
            return reverse("quote_detail", kwargs={"pk": self.pk})
        except NoReverseMatch:
            return "" 
Example #23
Source File: relations.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def get_url(self, obj, view_name, request, format):
        """
        Given an object, return the URL that hyperlinks to the object.

        May raise a `NoReverseMatch` if the `view_name` and `lookup_field`
        attributes are not configured to correctly match the URL conf.
        """
        # Unsaved objects will not yet have a valid URL.
        if hasattr(obj, 'pk') and obj.pk in (None, ''):
            return None

        lookup_value = getattr(obj, self.lookup_field)
        kwargs = {self.lookup_url_kwarg: lookup_value}
        return self.reverse(view_name, kwargs=kwargs, request=request, format=format) 
Example #24
Source File: views.py    From product-definition-center with MIT License 5 votes vote down vote up
def _get_detail_url(url_name, viewset, request, urlargs):
    if not hasattr(viewset, 'retrieve'):
        raise NoReverseMatch
    return reverse(
        url_name[:-5] + '-detail',
        request=request,
        args=urlargs + ['{%s}' % viewset.lookup_field],
        format=None
    ) 
Example #25
Source File: views.py    From product-definition-center with MIT License 5 votes vote down vote up
def _get_nested_list_url(url_name, viewset, request, urlargs):
    if not hasattr(viewset, 'list'):
        raise NoReverseMatch
    return reverse(
        url_name,
        request=request,
        args=urlargs,
        format=None
    ) 
Example #26
Source File: utilities.py    From open-humans with MIT License 5 votes vote down vote up
def active(context, pattern_or_urlname):
    """
    Return 'active' if the given URL or pattern is active.
    """
    try:
        pattern = "^" + reverse(pattern_or_urlname)
    except NoReverseMatch:
        pattern = pattern_or_urlname

    path = context.request.path

    if re.search(pattern, path):
        return "active"

    return "" 
Example #27
Source File: checks.py    From django-encrypted-filefield with GNU General Public License v3.0 5 votes vote down vote up
def fetch_url_check(app_configs, **kwargs):

    if not FETCH_URL_NAME:
        return []  # We've got bigger problems

    try:
        reverse(FETCH_URL_NAME, kwargs={"path": "anything"})
    except NoReverseMatch:
        return [Error(
            "django-encrypted-filefield requires that you define a url for "
            "the fetching the files."
        )]

    return [] 
Example #28
Source File: serializers.py    From mezzanine-api with MIT License 5 votes vote down vote up
def get_short_url(self, obj):
        """
        Get short URL of blog post like '/blog/<slug>/' using ``get_absolute_url`` if available.
        Removes dependency on reverse URLs of Mezzanine views when deploying Mezzanine only as an API backend.
        """
        try:
            url = obj.get_absolute_url()
        except NoReverseMatch:
            url = '/blog/' + obj.slug
        return url 
Example #29
Source File: defaulttags.py    From python2017 with MIT License 5 votes vote down vote up
def render(self, context):
        from django.urls import reverse, NoReverseMatch
        args = [arg.resolve(context) for arg in self.args]
        kwargs = {
            force_text(k, 'ascii'): v.resolve(context)
            for k, v in self.kwargs.items()
        }
        view_name = self.view_name.resolve(context)
        try:
            current_app = context.request.current_app
        except AttributeError:
            try:
                current_app = context.request.resolver_match.namespace
            except AttributeError:
                current_app = None
        # Try to look up the URL. If it fails, raise NoReverseMatch unless the
        # {% url ... as var %} construct is used, in which case return nothing.
        url = ''
        try:
            url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
        except NoReverseMatch:
            if self.asvar is None:
                raise

        if self.asvar:
            context[self.asvar] = url
            return ''
        else:
            if context.autoescape:
                url = conditional_escape(url)
            return url 
Example #30
Source File: shortcuts.py    From python2017 with MIT License 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: `urls.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 to.startswith(('./', '../')):
            return to

    # Next try a reverse URL resolution.
    try:
        return reverse(to, args=args, kwargs=kwargs)
    except 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