Dynamically update the URLs

I am trying to build the django admin site from scratch for a project and I will have my models and their urls. the urls of the models will be generated after I register a new model in my admin site. here are some code snippets to help you

from django.urls import path
from rest_admin import site


urlpatterns = [
    path("admin/", site.urls),
]

and here is the urls property and the get_urls method

def get_urls(self):
        from django.urls import path

        def wrap(view):
            def wrapper(*args, **kwargs):
                return self.admin_view(view)(*args, **kwargs)

            return wrapper

        urls = [
            path("", wrap(self.index), name="admin_index"),
            path("<app_label>", wrap(self.get_app)),
        ]
        for model, model_admin in self._registry.items():
            urls += [
                path("%s/%s/" % (model._meta.app_label, model._meta.model_name), include(model_admin.urls))
            ]
        return urls

    @property
    def urls(self):
        return self.get_urls(), "rest_admin"

and here is the same methods for the ModelAdmin

def get_urls(self):
        def wrap(view):
            def wrapper(*args, **kwargs):
                return self.admin_site.admin_view(view)(*args, **kwargs)
            return wrapper
        urls = [
            path("", wrap(self.list_model_view))
        ]
        return urls
    
    @property
    def urls(self):
        return self.get_urls()

but for example this gives me 404

@pytest.mark.django_db
@pytest.mark.admin_user
def test_list_model(client, access_token):
    site.register(Bar) 
    admin_site.register(Bar)
     
    url = "/admin/tests/bar/"
    res = client.get(url, headers=access_token.auth_header)
    
    print(res.status_code)

I know the problem. it’s all that the urls being set before I register the model so registering the model will not have any effect on the urls. so anyone have any idea how to solve this ?

well I just added this in case of someone needed a solution but I would welcome any better one.

in the urls.py I added this function

def add_urlpatterns(patterns):
    global urlpatterns
    if patterns:
        urlpatterns += patterns
    clear_url_caches()
1 Like