Django : How can I see a list of urlpatterns?

后端 未结 16 1769
有刺的猬
有刺的猬 2020-11-29 19:36

How can I see the current urlpatterns that \"reverse\" is looking in?

I\'m calling reverse in a view with an argument that I think should work, but doesn\'t. Any wa

16条回答
  •  北荒
    北荒 (楼主)
    2020-11-29 19:49

    You can create a dynamic import to gather all URL Patterns from each application in your project with a simple method like so:

    def get_url_patterns():
        from django.apps import apps
    
        list_of_all_url_patterns = list()
        for name, app in apps.app_configs.items():
            # you have a directory structure where you should be able to build the correct path
            # my example shows that apps.[app_name].urls is where to look
            mod_to_import = f'apps.{name}.urls'
            try:
                urls = getattr(importlib.import_module(mod_to_import), "urlpatterns")
                list_of_all_url_patterns.extend(urls)
            except ImportError as ex:
                # is an app without urls
                pass
    
        return list_of_all_url_patterns
    
    

    list_of_all_url_patterns = get_url_patterns()

    I recently used something like this to create a template tag to show active navigation links.

提交回复
热议问题