在 Django 中,可以自动将 URL 映射到视图方法吗?

发布于 2024-10-25 15:18:18 字数 431 浏览 1 评论 0原文

给定这样的视图:

# 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

山色无中 2024-11-01 15:18:18

我想你可以有一个捕获 url regexp 的视图,

r'^(?Pindex|list|about)/$', 'myview'

以及处理捕获参数的视图。

def myview(request, viewtype):
    if viewtype == 'index':
          return http.HttpResponse("I'm the index view")
    elif viewtype == 'list':
          return http.HttpResponse("I'm the list view')

但为了清晰起见,我真的建议将视图逻辑分开。遵循 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.

def myview(request, viewtype):
    if viewtype == 'index':
          return http.HttpResponse("I'm the index view")
    elif viewtype == 'list':
          return http.HttpResponse("I'm the list view')

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文