本文介绍了Django动态urlpatterns的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Django 构建一个简单的Web应用程序.我的用户分为多个组,例如 A组 B组等.

I'm building a simple web application with Django. My users are separated into multiple groups, for example Group A, Group B, etc.

我想做的是动态更新 urls.py 中的 urlpatterns 列表,这样我就可以在相同的URL端点上拥有不同的视图

What I want to do is to dynamically update urlpatterns list in urls.py so that I can have different views on same url endpoints.

例如,我想做这样的事情(我知道语法已关闭,只是为了演示我想要的东西)

For example, I'd like to do something like this (I know syntax is off, it's just to demonstrate what I want)

urlpatterns = [
    url(r'^$', views.homepage, name='homepage'),
    url(r'^login/$', views.BaseLogin.as_view(), name='core.login'),
    url(r'^logout/$', views.logout, name='core.logout'),
]  + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

if request.user in groupA:
    urlpatterns.append(url(r'^dash/', include('groupA.urls')))
else:
    urlpatterns.append(url(r'^dash/', include('groupB.urls')))

我如何最好地实现这一目标?

How would I best achieve this?

推荐答案

动态更改urlpattern不是一个好主意,但是您可以创建两个url conf mysite/groupA_root_urls.py mysite/groupB_root_urls.py .

It's not a good idea to change urlpatterns dynamically, but you could create two url confs mysite/groupA_root_urls.py and mysite/groupB_root_urls.py.

然后您可以编写一个中间件,将 request.urlconf 属性设置为'mysite.groupA_root_urls' 'mysite.groupA_root_urls' process_request 方法.

You can then write a middleware that sets the request.urlconf attribute to either 'mysite.groupA_root_urls' 'mysite.groupA_root_urls' in the process_request method.

然后Django将使用该urlconf代替 ROOT_URLCONF 设置中的conf.

Django will then use that urlconf instead of the conf from the ROOT_URLCONF setting.

这篇关于Django动态urlpatterns的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 20:39