在 Django 中,可以自动将 URL 映射到视图方法吗?
给定这样的视图:
# my_app/views.py
def index(request):
...
def list(request):
...
def about(request):
...
而不是在 urls.py
中为视图中的每个方法显式声明 url:
# urls.py
url(r'^index$', 'my_app.views.index'),
url(r'^list$', 'my_app.views.list'),
url(r'^about$', 'my_app.views.about'),
...
是否可以只为 URL 调度程序提供视图 (my_apps.views
code>) 并让它处理所有视图的方法?
Given a view like this:
# my_app/views.py
def index(request):
...
def list(request):
...
def about(request):
...
Instead of explicitly declaring the urls in urls.py
for each method in the view:
# urls.py
url(r'^index
Is it possible to just give the URL dispatcher the view (my_apps.views
) and have it handle all the view's methods?
, 'my_app.views.index'),
url(r'^list
Is it possible to just give the URL dispatcher the view (my_apps.views
) and have it handle all the view's methods?
, 'my_app.views.list'),
url(r'^about
Is it possible to just give the URL dispatcher the view (my_apps.views
) and have it handle all the view's methods?
, 'my_app.views.about'),
...
Is it possible to just give the URL dispatcher the view (my_apps.views
) and have it handle all the view's methods?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想你可以有一个捕获 url regexp 的视图,
r'^(?Pindex|list|about)/$', 'myview'
以及处理捕获参数的视图。
但为了清晰起见,我真的建议将视图逻辑分开。遵循 3 个不同的视图及其特定功能比遵循 3 个 if / then 语句要容易得多。
I suppose you can have one view that captures a url regexp,
r'^(?P<viewtype>index|list|about)/$', 'myview'
with a view that handles the captured parameter.
But I'd really recommend keeping your view logic separated for clarity. It's much easier to follow 3 different views with their specific functions than 3 if / then statements.