来自外部应用程序的 Django URL 参数
我正在使用 Django,并且我的项目的 urls.py 文件中有以下 URL。
(r'^user/(?P<username>[\w_\-\.]+)/my_app/', include('my_app.urls')),
(r'^user/(?P<username>[\w_\-\.]+)/my_other_app/', include('my_other_app.urls')),
...
目标是拥有一个使用用户用户名的应用程序,例如每个用户都有一个个人资料页面的个人资料应用程序。此应用程序中只有一个视图需要在 URL 中包含用户名(呈现个人资料页面的视图),但所有视图都必须采用 username
参数,即使它们不对其执行任何操作。
我怀疑 URL 参数的这种用法是错误的,因为它强制 my_app
的每个视图都将用户名作为参数(因为它是从 URL 调度程序传递的)。对我来说,外部组件(项目的 urls.py 文件)告诉 my_app
的 URL 要采用哪些参数是没有意义的。
这种用法正确吗?如果不是,我该怎么做?
I am using Django and I have the following URL in my project's urls.py file.
(r'^user/(?P<username>[\w_\-\.]+)/my_app/', include('my_app.urls')),
(r'^user/(?P<username>[\w_\-\.]+)/my_other_app/', include('my_other_app.urls')),
...
The goal is to have an application that uses the username of a user e.g. a profile application where every user has a profile page. Only one view in this application needs to have the username in the URL (the one that renders the profile page), but all the views must take a username
parameter even if they don't do anything with it.
I suspect that this usage of URL parameters is wrong because it forces every view of my_app
to take username as a parameter (because it's passed as from the URL dispatcher). To me it doesn't make sense for an external component (the project's urls.py file) to tell my_app
's URLs what parameters to take.
Is this usage correct? If not, how should I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这看起来确实有点奇怪。
您不能切换应用程序来查找用户名参数吗?在
my_app.urls
和后者下,只需在查找所需字段时使用username
字段即可。这样你的结构看起来更像:
/user/my_app/friends/hekevintran/
/user/my_other_app/connections/bartek/
这也同样有效并且不强制您的应用程序依赖根项目的上下文作为用户名。
It does seem kind of odd.
Could you not switch your apps to look for the username parameter instead? Under
my_app.urls
and the latter, just have theusername
field in the lookup on the fields you need.That way your structure looks more like:
/user/my_app/friends/hekevintran/
/user/my_other_app/connections/bartek/
Which works just as well and doesn't force your apps to rely on the context of your root project for the username.