Django的urlpatterns可以从字符串中创建吗?

ergxz8rk  于 12个月前  发布在  Go
关注(0)|答案(1)|浏览(114)

我有一个字符串列表,用于在Django布局模板中定义导航窗格。我想使用相同的列表来查看函数名称,并使用循环来相应地定义urls.py中的urlpatterns。
范例:

menu = ["register", "login", "logout"]
urlpatterns = [path("", views.index, name="index"),]

字符串
从上面,我想到达

urlpatterns = [
    path("", views.index, name="index"),
    path("/register", views.register, name="register"),
    path("/login", views.login, name="login"),
    path("/logout", views.logout, name="logout"),
]


我可以将路由作为str传递,将kwargs作为dict传递,但是很难将字符串转换为可调用的视图函数的名称。这可能吗?

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))

7fyelxc5

7fyelxc51#

是的,您可以用途:

menu = ['register', 'login', 'logout']
urlpatterns = [
    path('', views.index, name='index'),
    *[path(f'{name}/', getattr(views, name), name=name) for name in menu],
]

字符串

相关问题