django.urls.exceptions NoReverseMatch Python Code Examples

NoReverseMatch (source code) is a Django exception that is raised when a URL cannot be matched against any string or regular express in your URL configuration.

A URL matching problem is often caused by missing arguments or supplying too many arguments. For example, let's say you have a blog project with URLs like "myblog.com/2019/10/title-slug", where 2019 is the year, 10 is the month and title-slug is the article's title as a slug. A miss could happen if you have a URL configuration that is trying to find a blog post with the year and the month in the path, but your application only specifies the year without the month.

Example 1 from django-angular

django-angular (project examples website) is a library with helper code to make it easier to use Angular as the front-end to Django projects. The code for django-angular is open source under the MIT license.

django-angular / djng / core / urlresolvers.py

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from inspect import isclass

from django.utils import six
from django.urls import (get_resolver, get_urlconf, resolve, 
                         reverse, NoReverseMatch)
from django.core.exceptions import ImproperlyConfigured

try:
    from django.utils.module_loading import import_string
except ImportError:
    from django.utils.module_loading \
        import import_by_path as import_string

from djng.views.mixins import JSONResponseMixin


def _get_remote_methods_for(view_object, url):
    # view_object can be a view class or instance
    result = {}
    for field in dir(view_object):
        member = getattr(view_object, field, None)
        if callable(member) and hasattr(member, 'allow_rmi'):
            config = {
                'url': url,
                'method': getattr(member, 'allow_rmi'),
                'headers': {'DjNg-Remote-Method': field},
            }
            result.update({field: config})
    return result


def get_all_remote_methods(resolver=None, ns_prefix=''):
    """
    Returns a dictionary to be used for calling 
    ``djangoCall.configure()``, which itself extends the
    Angular API to the client, offering him to call remote methods.
    """
    if not resolver:
        resolver = get_resolver(get_urlconf())
    result = {}
    for name in resolver.reverse_dict.keys():
        if not isinstance(name, six.string_types):
            continue
        try:
            url = reverse(ns_prefix + name)
            resmgr = resolve(url)
            ViewClass = import_string('{0}.{1}'.format(\
                resmgr.func.__module__, resmgr.func.__name__))
            if isclass(ViewClass) and issubclass(ViewClass, 
                                                 JSONResponseMixin):
                result[name] = _get_remote_methods_for(ViewClass, 
                                                       url)
        except (NoReverseMatch, ImproperlyConfigured):
            pass
    for namespace, ns_pattern in resolver.namespace_dict.items():
        sub_res = get_all_remote_methods(ns_pattern[1], 
                                         ns_prefix + namespace + ':')
        if sub_res:
            result[namespace] = sub_res
    return result


def get_current_remote_methods(view):
    if isinstance(view, JSONResponseMixin):
        return _get_remote_methods_for(view, 
                                       view.request.path_info)
1. Introduction 2. Development Environments 3. Data 4. Web Development 5. Deployment 6. DevOps Changelog What Full Stack Means About the Author Future Directions Page Statuses Django Code Examples django.urls.path django.conf.urls.url django.contrib.admin django.db.models Model django.dispatch Signal django.db.models.signal django.core.mail.send_mail django.core.mail.messages EmailMessage django.conf settings django.forms django.contrib.admin.sites register django.core.management.base BaseCommand django.utils.timezone django.contrib.auth get_user_model django.contrib.auth.decorators login_required django.core.exceptions ImproperlyConfigured django.utils.html format_html django.contrib.auth.hashers make_password django.http Http404 django.http HttpResponse django.http HttpResponseForbidden django.http HttpResponseBadRequest django.contrib.admin.filters SimpleListFilter django.urls.exceptions NoReverseMatch django.http HttpResponsePermanentRedirect django.http HttpResponseNotModified django.http HttpResponseRedirect django.apps.config AppConfig django.db OperationalError flask_sqlalchemy.SQLAlchemy Model django.db.models CharField django.db.models TextField django.db.models BooleanField flask request flask redirect django.db.models DateTimeField django.db.models IntegerField django.db.models AutoField django.db.models DateField django.db.models FileField django.template.response TemplateResponse django.template.response SimpleTemplateResponse SQLAlchemy Model Examples django.urls reverse_lazy Flask Core and Extensions Code Examples ...or view the full table of contents.

Full Stack Python

Full Stack Python is an open book that explains concepts in plain language and provides helpful resources for those topics.
Updates via Twitter & Facebook.

Matt Makai 2012-2019