Python django.urls.Resolver404() Examples

The following are 30 code examples of django.urls.Resolver404(). 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: middleware.py    From django-modeladmin-reorder with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def process_template_response(self, request, response):
        try:
            url = resolve(request.path_info)
        except Resolver404:
            return response
        if not url.app_name == 'admin' and \
                url.url_name not in ['index', 'app_list']:
            # current view is not a django admin index
            # or app_list view, bail out!
            return response

        try:
            app_list = response.context_data['app_list']
        except KeyError:
            # there is no app_list! nothing to reorder
            return response

        self.init_config(request, app_list)
        ordered_app_list = self.get_app_list()
        response.context_data['app_list'] = ordered_app_list
        return response 
Example #2
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_nonmatching_urls(self):
        test_data = (
            ('int', {'-1', 'letters'}),
            ('str', {'', '/'}),
            ('path', {''}),
            ('slug', {'', 'stars*notallowed'}),
            ('uuid', {
                '',
                '9da9369-838e-4750-91a5-f7805cd82839',
                '39da9369-838-4750-91a5-f7805cd82839',
                '39da9369-838e-475-91a5-f7805cd82839',
                '39da9369-838e-4750-91a-f7805cd82839',
                '39da9369-838e-4750-91a5-f7805cd8283',
            }),
        )
        for url_name, url_suffixes in test_data:
            for url_suffix in url_suffixes:
                url = '/%s/%s/' % (url_name, url_suffix)
                with self.subTest(url=url), self.assertRaises(Resolver404):
                    resolve(url) 
Example #3
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_nonmatching_urls(self):
        test_data = (
            ('int', {'-1', 'letters'}),
            ('str', {'', '/'}),
            ('path', {''}),
            ('slug', {'', 'stars*notallowed'}),
            ('uuid', {
                '',
                '9da9369-838e-4750-91a5-f7805cd82839',
                '39da9369-838-4750-91a5-f7805cd82839',
                '39da9369-838e-475-91a5-f7805cd82839',
                '39da9369-838e-4750-91a-f7805cd82839',
                '39da9369-838e-4750-91a5-f7805cd8283',
            }),
        )
        for url_name, url_suffixes in test_data:
            for url_suffix in url_suffixes:
                url = '/%s/%s/' % (url_name, url_suffix)
                with self.subTest(url=url), self.assertRaises(Resolver404):
                    resolve(url) 
Example #4
Source File: url_stats.py    From Inboxen with GNU Affero General Public License v3.0 6 votes vote down vote up
def count_urls(self, file_obj):
        urls = {}
        non_match = set()
        for url in file_obj:
            url = url.strip()
            try:
                name = resolve(url).url_name
            except Resolver404:
                non_match.add(url)
                continue

            if name in urls:
                urls[name] = urls[name] + 1
            else:
                urls[name] = 1

        return urls, non_match 
Example #5
Source File: menu_helpers.py    From djangocms-spa-vue-js with MIT License 6 votes vote down vote up
def get_node_template_name(node):
    try:
        view = get_view_from_url(node.get_absolute_url())
    except (AttributeError, Resolver404):
        return settings.DJANGOCMS_SPA_VUE_JS_ERROR_404_TEMPLATE
    if view.__module__ == 'cms.views':
        template = node.attr.get('template')
        if template:
            return template
        else:
            try:
                return node.attr.get('cms_page').get_template()
            except:
                return settings.DJANGOCMS_SPA_VUE_JS_ERROR_404_TEMPLATE
    else:
        try:
            return view.template_name
        except AttributeError:
            return settings.DJANGOCMS_SPA_DEFAULT_TEMPLATE 
Example #6
Source File: api.py    From c3nav with Apache License 2.0 6 votes vote down vote up
def resolved(self):
        resolved = None
        path = self.kwargs.get('path', '')
        if path:
            try:
                resolved = resolve('/editor/'+path+'/')
            except Resolver404:
                pass

        if not resolved:
            try:
                resolved = resolve('/editor/'+path)
            except Resolver404:
                pass

        self.request.sub_resolver_match = resolved

        return resolved 
Example #7
Source File: test_views.py    From edx-search with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_url_resolution(self):
        """ make sure that the url is resolved as expected """
        resolver = resolve('/')
        self.assertEqual(resolver.view_name, 'do_search')

        with self.assertRaises(Resolver404):
            resolver = resolve('/blah')

        resolver = resolve('/edX/DemoX/Demo_Course')
        self.assertEqual(resolver.view_name, 'do_search')
        self.assertEqual(resolver.kwargs['course_id'], 'edX/DemoX/Demo_Course') 
Example #8
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_resolve_value_error_means_no_match(self):
        @DynamicConverter.register_to_python
        def raises_value_error(value):
            raise ValueError()
        with self.assertRaises(Resolver404):
            resolve('/dynamic/abc/') 
Example #9
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_resolve_value_error_means_no_match(self):
        @DynamicConverter.register_to_python
        def raises_value_error(value):
            raise ValueError()
        with self.assertRaises(Resolver404):
            resolve('/dynamic/abc/') 
Example #10
Source File: edit.py    From Inboxen with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_success_url(self):
        referer = self.request.META.get("HTTP_REFERER", "/user/home/")
        try:
            url_name = resolve(referer).url_name
            self.success_views.index(url_name)
            return referer
        except (ValueError, Resolver404):
            return reverse("user-home") 
Example #11
Source File: test_utilities.py    From openstax-cms with GNU Affero General Public License v3.0 5 votes vote down vote up
def assertPathDoesNotRedirectToTrailingSlash(test, path):
    try:
        resolve(path)
    except Resolver404:
        test.fail('The path {} cannot be found'.format(path))

    response = test.client.get(path)

    if (type(response).__name__ == 'HttpResponsePermanentRedirect' or
       type(response).__name__ == 'HttpResponsePermanentRedirect'):
       test.assertNotEqual(response.url, path + "/") 
Example #12
Source File: model_factory.py    From django-silk with MIT License 5 votes vote down vote up
def view_name(self):
        try:
            resolved = resolve(self.request.path_info)
        except Resolver404:
            return None

        return resolved.view_name 
Example #13
Source File: model_factory.py    From django-silk with MIT License 5 votes vote down vote up
def view_name(self):
        try:
            resolved = resolve(self.request.path_info)
        except Resolver404:
            return None

        return resolved.view_name 
Example #14
Source File: relations.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def to_internal_value(self, data):
        request = self.context.get('request', None)
        try:
            http_prefix = data.startswith(('http:', 'https:'))
        except AttributeError:
            self.fail('incorrect_type', data_type=type(data).__name__)

        if http_prefix:
            # If needed convert absolute URLs to relative path
            data = urlparse.urlparse(data).path
            prefix = get_script_prefix()
            if data.startswith(prefix):
                data = '/' + data[len(prefix):]

        data = uri_to_iri(data)

        try:
            match = resolve(data)
        except Resolver404:
            self.fail('no_match')

        try:
            expected_viewname = request.versioning_scheme.get_versioned_viewname(
                self.view_name, request
            )
        except AttributeError:
            expected_viewname = self.view_name

        if match.view_name != expected_viewname:
            self.fail('incorrect_match')

        try:
            return self.get_object(match.view_name, match.args, match.kwargs)
        except (ObjectDoesNotExist, TypeError, ValueError):
            self.fail('does_not_exist') 
Example #15
Source File: menu_helpers.py    From djangocms-spa-vue-js with MIT License 5 votes vote down vote up
def get_node_route_for_app_model(request, node, route_data):
    # Set name and component of the route.
    route_data['component'] = node.attr.get('component')
    route_data['name'] = node.attr.get('vue_js_router_name')

    # Add the link to fetch the data from the API.
    route_data['api']['fetch'] = {
        'url': node.attr.get('fetch_url'),
    }

    try:
        request_url_name = resolve(request.path).url_name
        node_url_name = resolve(node.get_absolute_url()).url_name
    except Resolver404:
        resolver_match = False
    else:
        resolver_match = request_url_name == node_url_name

    is_selected_node = request.path == node.get_absolute_url() or resolver_match
    if is_selected_node:
        # We need to prepare the initial structure of the fetched data. The actual data is added by the view.
        route_data['api']['fetched'] = {
            'response': {
                'data': {}
            }
        }
        route_data['params'] = node.attr.get('url_params', {})

    meta_id = node.attr.get('id')
    if meta_id:
        route_data['meta'] = {
            'id': meta_id
        }

    route_data['path'] = node.get_absolute_url()
    return route_data 
Example #16
Source File: admin_urls.py    From python2017 with MIT License 5 votes vote down vote up
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) 
Example #17
Source File: import_export_task.py    From kpi with GNU Affero General Public License v3.0 5 votes vote down vote up
def _resolve_url_to_asset_or_collection(item_path):
    if item_path.startswith(('http', 'https')):
        item_path = urlparse(item_path).path
    try:
        match = resolve(item_path)
    except Resolver404:
        # If the app is mounted in uWSGI with a path prefix, try to resolve
        # again after removing the prefix
        match = resolve(remove_string_prefix(item_path, settings.KPI_PREFIX))

    uid = match.kwargs.get('uid')
    if match.url_name == 'asset-detail':
        return 'asset', Asset.objects.get(uid=uid)
    elif match.url_name == 'collection-detail':
        return 'collection', Collection.objects.get(uid=uid) 
Example #18
Source File: view_helpers.py    From django-htk with MIT License 5 votes vote down vote up
def get_resolver_matches_chain(request, data=None):
    """Walk the current request URL path up to the top, attempting to resolve along the way
    """
    from django.urls import Resolver404
    from django.urls import resolve
    resolver_matches_chain = []
    path = request.path
    resolver_matches_chain.append((path, request.resolver_match,))
    while path:
        try:
            path = path[:path.rindex('/')]
            resolver_match = resolve(path)
            resolver_matches_chain.append((path, resolver_match))
        except Resolver404:
            # could not resolve without '/'
            path_with_slash = path + '/'
            if request.path != path_with_slash:
                try:
                    resolver_match = resolve(path_with_slash)
                    resolver_matches_chain.append((path_with_slash, resolver_match))
                except Resolver404:
                    pass
        except ValueError:
            # '/' substring not found
            break
    return resolver_matches_chain 
Example #19
Source File: middleware.py    From django-request-logging with MIT License 5 votes vote down vote up
def _should_log_route(self, request):
        # request.urlconf may be set by middleware or application level code.
        # Use this urlconf if present or default to None.
        # https://docs.djangoproject.com/en/2.1/topics/http/urls/#how-django-processes-a-request
        # https://docs.djangoproject.com/en/2.1/ref/request-response/#attributes-set-by-middleware
        urlconf = getattr(request, 'urlconf', None)

        try:
            route_match = resolve(request.path, urlconf=urlconf)
        except Resolver404:
            return False, None

        method = request.method.lower()
        view = route_match.func
        func = view
        # This is for "django rest framework"
        if hasattr(view, 'cls'):
            if hasattr(view, 'actions'):
                actions = view.actions
                method_name = actions.get(method)
                if method_name:
                    func = getattr(view.cls, view.actions[method], None)
            else:
                func = getattr(view.cls, method, None)
        elif hasattr(view, 'view_class'):
            # This is for django class-based views
            func = getattr(view.view_class, method, None)
        no_logging = getattr(func, NO_LOGGING_ATTR, False)
        no_logging_msg = getattr(func, NO_LOGGING_MSG_ATTR, None)
        return no_logging, no_logging_msg 
Example #20
Source File: admin_urls.py    From python with Apache License 2.0 5 votes vote down vote up
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) 
Example #21
Source File: views.py    From healthchecks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _is_whitelisted(redirect_url):
    if not redirect_url:
        return False

    parsed = urlparse(redirect_url)
    try:
        match = resolve(parsed.path)
    except Resolver404:
        return False

    return match.url_name in NEXT_WHITELIST 
Example #22
Source File: admin_urls.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
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 = {}

    if opts and preserved_filters:
        preserved_filters = dict(parse_qsl(preserved_filters))

        match_url = '/%s' % unquote(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) 
Example #23
Source File: forms.py    From zing with GNU General Public License v3.0 5 votes vote down vote up
def clean(self):
        if "checks" in self.errors:
            del self.errors["checks"]
            self.cleaned_data["checks"] = None
        if "user" in self.errors:
            del self.errors["user"]
            self.cleaned_data["user"] = self.request_user
        if self.errors:
            return
        pootle_path = self.cleaned_data.get("path")
        path_keys = ["project_code", "language_code", "dir_path", "filename"]
        try:
            path_kwargs = {
                k: v for k, v in resolve(pootle_path).kwargs.items() if k in path_keys
            }
        except Resolver404:
            raise forms.ValidationError("Unrecognised path")
        self.cleaned_data.update(path_kwargs)
        sort_on = "units"
        if "filter" in self.cleaned_data:
            unit_filter = self.cleaned_data["filter"]
            if unit_filter in ("suggestions", "user-suggestions"):
                sort_on = "suggestions"
            elif unit_filter in ("user-submissions",):
                sort_on = "submissions"
        sort_by_param = self.cleaned_data["sort"]
        self.cleaned_data["sort_by"] = ALLOWED_SORTS[sort_on].get(sort_by_param)
        self.cleaned_data["sort_on"] = sort_on 
Example #24
Source File: middleware.py    From online-judge with GNU Affero General Public License v3.0 5 votes vote down vote up
def __call__(self, request):
        try:
            callback, args, kwargs = resolve(request.path_info, getattr(request, 'urlconf', None))
        except Resolver404:
            callback, args, kwargs = None, None, None

        if getattr(callback, 'short_circuit_middleware', False):
            return callback(request, *args, **kwargs)
        return self.get_response(request) 
Example #25
Source File: resolution.py    From django-webmention with MIT License 5 votes vote down vote up
def url_resolves(url):
    try:
        resolve(urlparse(url).path)
    except Resolver404:
        return False
    return True 
Example #26
Source File: admin_urls.py    From bioforum with MIT License 5 votes vote down vote up
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 = {}

    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) 
Example #27
Source File: __init__.py    From django-subadmin with MIT License 5 votes vote down vote up
def add_preserved_filters(self, 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_changelist' % self.get_base_viewname()
                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) 
Example #28
Source File: debug.py    From python2017 with MIT License 4 votes vote down vote up
def technical_404_response(request, exception):
    "Create a technical 404 error response. The exception should be the Http404."
    try:
        error_url = exception.args[0]['path']
    except (IndexError, TypeError, KeyError):
        error_url = request.path_info[1:]  # Trim leading slash

    try:
        tried = exception.args[0]['tried']
    except (IndexError, TypeError, KeyError):
        tried = []
    else:
        if (not tried or (                  # empty URLconf
            request.path == '/' and
            len(tried) == 1 and             # default URLconf
            len(tried[0]) == 1 and
            getattr(tried[0][0], 'app_name', '') == getattr(tried[0][0], 'namespace', '') == 'admin'
        )):
            return default_urlconf(request)

    urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
    if isinstance(urlconf, types.ModuleType):
        urlconf = urlconf.__name__

    caller = ''
    try:
        resolver_match = resolve(request.path)
    except Resolver404:
        pass
    else:
        obj = resolver_match.func

        if hasattr(obj, '__name__'):
            caller = obj.__name__
        elif hasattr(obj, '__class__') and hasattr(obj.__class__, '__name__'):
            caller = obj.__class__.__name__

        if hasattr(obj, '__module__'):
            module = obj.__module__
            caller = '%s.%s' % (module, caller)

    t = DEBUG_ENGINE.from_string(TECHNICAL_404_TEMPLATE)
    c = Context({
        'urlconf': urlconf,
        'root_urlconf': settings.ROOT_URLCONF,
        'request_path': error_url,
        'urlpatterns': tried,
        'reason': force_bytes(exception, errors='replace'),
        'request': request,
        'settings': get_safe_settings(),
        'raising_view_name': caller,
    })
    return HttpResponseNotFound(t.render(c), content_type='text/html') 
Example #29
Source File: debug.py    From python with Apache License 2.0 4 votes vote down vote up
def technical_404_response(request, exception):
    "Create a technical 404 error response. The exception should be the Http404."
    try:
        error_url = exception.args[0]['path']
    except (IndexError, TypeError, KeyError):
        error_url = request.path_info[1:]  # Trim leading slash

    try:
        tried = exception.args[0]['tried']
    except (IndexError, TypeError, KeyError):
        tried = []
    else:
        if (not tried or (                  # empty URLconf
            request.path == '/' and
            len(tried) == 1 and             # default URLconf
            len(tried[0]) == 1 and
            getattr(tried[0][0], 'app_name', '') == getattr(tried[0][0], 'namespace', '') == 'admin'
        )):
            return default_urlconf(request)

    urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
    if isinstance(urlconf, types.ModuleType):
        urlconf = urlconf.__name__

    caller = ''
    try:
        resolver_match = resolve(request.path)
    except Resolver404:
        pass
    else:
        obj = resolver_match.func

        if hasattr(obj, '__name__'):
            caller = obj.__name__
        elif hasattr(obj, '__class__') and hasattr(obj.__class__, '__name__'):
            caller = obj.__class__.__name__

        if hasattr(obj, '__module__'):
            module = obj.__module__
            caller = '%s.%s' % (module, caller)

    t = DEBUG_ENGINE.from_string(TECHNICAL_404_TEMPLATE)
    c = Context({
        'urlconf': urlconf,
        'root_urlconf': settings.ROOT_URLCONF,
        'request_path': error_url,
        'urlpatterns': tried,
        'reason': force_bytes(exception, errors='replace'),
        'request': request,
        'settings': get_safe_settings(),
        'raising_view_name': caller,
    })
    return HttpResponseNotFound(t.render(c), content_type='text/html') 
Example #30
Source File: debug.py    From Hands-On-Application-Development-with-PyCharm with MIT License 4 votes vote down vote up
def technical_404_response(request, exception):
    """Create a technical 404 error response. `exception` is the Http404."""
    try:
        error_url = exception.args[0]['path']
    except (IndexError, TypeError, KeyError):
        error_url = request.path_info[1:]  # Trim leading slash

    try:
        tried = exception.args[0]['tried']
    except (IndexError, TypeError, KeyError):
        tried = []
    else:
        if (not tried or (                  # empty URLconf
            request.path == '/' and
            len(tried) == 1 and             # default URLconf
            len(tried[0]) == 1 and
            getattr(tried[0][0], 'app_name', '') == getattr(tried[0][0], 'namespace', '') == 'admin'
        )):
            return default_urlconf(request)

    urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
    if isinstance(urlconf, types.ModuleType):
        urlconf = urlconf.__name__

    caller = ''
    try:
        resolver_match = resolve(request.path)
    except Resolver404:
        pass
    else:
        obj = resolver_match.func

        if hasattr(obj, '__name__'):
            caller = obj.__name__
        elif hasattr(obj, '__class__') and hasattr(obj.__class__, '__name__'):
            caller = obj.__class__.__name__

        if hasattr(obj, '__module__'):
            module = obj.__module__
            caller = '%s.%s' % (module, caller)

    with Path(CURRENT_DIR, 'templates', 'technical_404.html').open() as fh:
        t = DEBUG_ENGINE.from_string(fh.read())
    c = Context({
        'urlconf': urlconf,
        'root_urlconf': settings.ROOT_URLCONF,
        'request_path': error_url,
        'urlpatterns': tried,
        'reason': str(exception),
        'request': request,
        'settings': get_safe_settings(),
        'raising_view_name': caller,
    })
    return HttpResponseNotFound(t.render(c), content_type='text/html')