Is it possible to make Django urlpatterns from a string?
Question:
I have a list of strings that is used to define navigation pane in a Django layout template. I want to use the same list for view function names and use a loop to define urlpatterns in urls.py accordingly.
Example:
menu = ["register", "login", "logout"]
urlpatterns = [path("", views.index, name="index"),]
From the above, I want to arrive at
urlpatterns = [
path("", views.index, name="index"),
path("/register", views.register, name="register"),
path("/login", views.login, name="login"),
path("/logout", views.logout, name="logout"),
]
I am able to pass the route as str and kwargs as a dict, but struggling with transforming the string into a name of a callable views function. Is this possible?
for i in menu:
url = f'"/{i}"' #works when passed as parameter to path()
rev = {"name": i} #works when passed as parameter to path()
v = f"views.{i}" #this does not work
v = include(f"views.{i}", namespace="myapp") #this does not work either
urlpatterns.append(path(url, v, rev))
Answers:
Yes, you can use:
menu = ['register', 'login', 'logout']
urlpatterns = [
path('', views.index, name='index'),
*[path(f'{name}/', getattr(views, name), name=name) for name in menu],
]
I have a list of strings that is used to define navigation pane in a Django layout template. I want to use the same list for view function names and use a loop to define urlpatterns in urls.py accordingly.
Example:
menu = ["register", "login", "logout"]
urlpatterns = [path("", views.index, name="index"),]
From the above, I want to arrive at
urlpatterns = [
path("", views.index, name="index"),
path("/register", views.register, name="register"),
path("/login", views.login, name="login"),
path("/logout", views.logout, name="logout"),
]
I am able to pass the route as str and kwargs as a dict, but struggling with transforming the string into a name of a callable views function. Is this possible?
for i in menu:
url = f'"/{i}"' #works when passed as parameter to path()
rev = {"name": i} #works when passed as parameter to path()
v = f"views.{i}" #this does not work
v = include(f"views.{i}", namespace="myapp") #this does not work either
urlpatterns.append(path(url, v, rev))
Yes, you can use:
menu = ['register', 'login', 'logout']
urlpatterns = [
path('', views.index, name='index'),
*[path(f'{name}/', getattr(views, name), name=name) for name in menu],
]