Created
October 24, 2017 09:13
-
-
Save Bobsans/c8e9f3e3f714ae61488f1c978c97fa04 to your computer and use it in GitHub Desktop.
Get dict of links from django urls.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from django.core.exceptions import ImproperlyConfigured | |
| from django.urls import NoReverseMatch, get_resolver, get_urlconf, reverse | |
| def get_apps_urls(resolver=None, nsprefix='', urlprefix=''): | |
| result = {} | |
| if not resolver: | |
| resolver = get_resolver(get_urlconf()) | |
| for name, urlattrs in resolver.reverse_dict.items(): | |
| if isinstance(name, str): | |
| try: | |
| url = reverse(nsprefix + name) | |
| result[nsprefix + name] = url | |
| except NoReverseMatch: | |
| result[nsprefix + name] = f'/{urlprefix}{urlattrs[0][0][0]}' % {k: (':' + k) for k in urlattrs[0][0][1]} | |
| except ImproperlyConfigured: | |
| pass | |
| for namespace, nspattern in resolver.namespace_dict.items(): | |
| if namespace not in ['admin']: | |
| nsres = get_apps_urls(nspattern[1], nsprefix + namespace + ':', nspattern[0]) | |
| if nsres: | |
| result.update(nsres) | |
| return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment