我们从Python开源项目中,提取了以下19个代码示例,用于说明如何使用django.urls.Resolver404()。
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 not template: try: template = node.attr.get('cms_page').get_template() except: template = settings.DJANGOCMS_SPA_VUE_JS_ERROR_404_TEMPLATE return template else: return view.template_name
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)
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
def url(self): url = self.get('ic-current-url', None) match = None if url is not None: url = url.strip() url = urlparse(url) if url.path: try: match = resolve(url.path) except Resolver404: pass return UrlMatch(url, match)
def bulk_destroy(self, request, *args, **kwargs): if not request.data: return Response(status=status.HTTP_400_BAD_REQUEST) qs = self.get_queryset() ids = [] for url in request.data: try: http_prefix = url.startswith(('http:', 'https:')) except AttributeError: return Response(status=status.HTTP_400_BAD_REQUEST) if http_prefix: # If needed convert absolute URLs to relative path url = urlparse(url).path prefix = get_script_prefix() if url.startswith(prefix): url = '/' + url[len(prefix):] try: match = resolve(url) except Resolver404: return Response(status=status.HTTP_400_BAD_REQUEST) try: pk = int(match.kwargs.get('pk')) except (ValueError, TypeError): return Response(status=status.HTTP_400_BAD_REQUEST) ids.append(pk) if not ids: return Response(status=status.HTTP_400_BAD_REQUEST) qs.filter(id__in=ids).delete() return Response(status=status.HTTP_204_NO_CONTENT)
def create_new_url(url): match_kamerstuk = re.match("kst-(\d+)-(\d+)", url) match_dossier = re.match("/dossier/(\d+)", url) new_url = '' if match_kamerstuk: dossier_id = match_kamerstuk.group(1) sub_id = match_kamerstuk.group(2) kamerstukken = Kamerstuk.objects.filter(id_main=dossier_id, id_sub=sub_id) if kamerstukken.exists(): new_url = reverse('kamerstuk', args=(dossier_id, sub_id,)) elif match_dossier: dossier_id = match_dossier.group(1) if Dossier.objects.filter(dossier_id=dossier_id).exists(): new_url = reverse('dossier-timeline', args=(dossier_id,)) if not new_url: try: resolve(url) openkamer_url = True except Resolver404: openkamer_url = False if openkamer_url or url[0] == '#' or 'http' in url: # openkamer, anchor or external url new_url = url else: if url[0] != '/': url = '/' + url new_url = 'https://zoek.officielebekendmakingen.nl' + url return new_url
def view_passes_test(view_name, path, **kwargs): # Special case for tag included everywhere if view_name == '__all__': return True try: view = resolve(path, **kwargs) return view_name == view.view_name except Resolver404: return False
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')