本文整理汇总了Python中django.urls.NoReverseMatch方法的典型用法代码示例。如果您正苦于以下问题:Python urls.NoReverseMatch方法的具体用法?Python urls.NoReverseMatch怎么用?Python urls.NoReverseMatch使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.urls
的用法示例。
在下文中一共展示了urls.NoReverseMatch方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _get_sitemap_full_url
# 需要导入模块: from django import urls [as 别名]
# 或者: from django.urls import NoReverseMatch [as 别名]
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)
示例2: get_model_doc_type_map
# 需要导入模块: from django import urls [as 别名]
# 或者: from django.urls import NoReverseMatch [as 别名]
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}
示例3: test_admin_login
# 需要导入模块: from django import urls [as 别名]
# 或者: from django.urls import NoReverseMatch [as 别名]
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)
示例4: get_redirect_url
# 需要导入模块: from django import urls [as 别名]
# 或者: from django.urls import NoReverseMatch [as 别名]
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
示例5: _resolve_prerequisite_links
# 需要导入模块: from django import urls [as 别名]
# 或者: from django.urls import NoReverseMatch [as 别名]
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
示例6: test_no_anonymous_access
# 需要导入模块: from django import urls [as 别名]
# 或者: from django.urls import NoReverseMatch [as 别名]
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)
示例7: test_resolve_email_with_plus_url
# 需要导入模块: from django import urls [as 别名]
# 或者: from django.urls import NoReverseMatch [as 别名]
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)
示例8: get_url_with_resource
# 需要导入模块: from django import urls [as 别名]
# 或者: from django.urls import NoReverseMatch [as 别名]
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
示例9: substitute_urls
# 需要导入模块: from django import urls [as 别名]
# 或者: from django.urls import NoReverseMatch [as 别名]
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)
示例10: reverse
# 需要导入模块: from django import urls [as 别名]
# 或者: from django.urls import NoReverseMatch [as 别名]
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)
示例11: get
# 需要导入模块: from django import urls [as 别名]
# 或者: from django.urls import NoReverseMatch [as 别名]
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)
示例12: optional_logout
# 需要导入模块: from django import urls [as 别名]
# 或者: from django.urls import NoReverseMatch [as 别名]
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)
示例13: get
# 需要导入模块: from django import urls [as 别名]
# 或者: from django.urls import NoReverseMatch [as 别名]
def get(self, request, *args, **kwargs):
ret = {}
# Get the version namespace
namespace = getattr(request.resolver_match, "namespace", "")
for ns in namespace.split(":"):
if re.match(r"v[0-9]+", ns, re.I):
namespace = ns
break
if self.urlconf:
urlconf = self.urlconf
else:
urlconf = import_module(settings.ROOT_URLCONF)
endpoints = get_api_endpoints(urlconf.urlpatterns)
for endpoint in sorted(endpoints, key=lambda e: e["pattern"].name):
name = endpoint["pattern"].name
if endpoint["method"] == "GET" and namespace in endpoint["namespace"].split(":"):
allow_cdn = getattr(endpoint["pattern"], "allow_cdn", True)
if not allow_cdn and settings.APP_SERVER_URL:
base = settings.APP_SERVER_URL
else:
base = request.build_absolute_uri()
try:
full_name = (
f'{endpoint["namespace"]}:{name}' if endpoint["namespace"] else name
)
path = reverse(full_name, *args, **kwargs)
except NoReverseMatch:
continue
full_url = urljoin(base, path)
ret[name] = full_url
return Response(ret)
示例14: active_link
# 需要导入模块: from django import urls [as 别名]
# 或者: from django.urls import NoReverseMatch [as 别名]
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 ''
示例15: get_admin_url
# 需要导入模块: from django import urls [as 别名]
# 或者: from django.urls import NoReverseMatch [as 别名]
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