2

I need to list all url names, but I can't find this item dynamically in django.

I was trying to list all urls with code but that's not working. Because I am calling that function in model file and in choices part and that returns an empty list.

This is my code I use to extract all url names:

def get_url_names():
    list_of_url_names = list()
    list_of_all_urls = list()
    for name, app in apps.app_configs.items():
        mod_to_import = f'{name}.urls'
        try:
            urls = getattr(importlib.import_module(mod_to_import), "urlpatterns")
            list_of_all_urls.extend(urls)
        except ImportError as ex:
            # is an app without urls
            pass

    for url in list_of_all_urls:
        list_of_url_names.append(url.name)

    return list_of_url_names

but this code does not run in model file, because of raise import error. in that model import this function and this function imports that package again and that is a circuit import. I can not use this func in model and i need to use it where makemigration command executes that before model file and save that data to database or a text file. that's not optimal and I don't know where should I use it?

How do I use this func:

class RelativeLink(models.Model):
    name = models.CharField(max_length=300, verbose_name='Link Name')
    url = models.URLField(max_length=500, verbose_name='Link URl')
    page = models.CharField(max_length=500, choices=get_url_names())
haduki
  • 1,145
  • 5
  • 23

0 Answers0