简体   繁体   English

如何区分两个相似的模式网址?

[英]How to differentiate two similar pattern urls?

url(r'^foobar/(?P<field1>.+)/$', views.foo, name="foo"),
url(r'^foobar/(?P<field2>.+)/$', views.bar , name="bar"),

These are similar pattern url in django. 这些是Django中类似的模式url。 But it takes different parameters. 但是它采用不同的参数。 How can I differentiate between them. 我该如何区分它们。

if the parameters match the same regex, (as in your example above), you'll need to move any further dispatching into the view itself. 如果参数与相同的正则表达式匹配(如上面的示例中所示),则需要将所有其他分派移至视图本身。 so have both urls map to the same view, and do some further logic in the view to decide what to do next, eg: 因此,将两个网址都映射到同一个视图,并在视图中执行一些进一步的逻辑来决定下一步要执行的操作,例如:

 def dispatcher(request, arg):
      if arg == 1:
           return fun1(request, arg)
      else:
           return fun2(request, arg)

(note that this example could be done in urls: (请注意,此示例可以在url中完成:

url(r'^foobar/(?P<field1>1)/$', fun1)
url(r'^foobar/(?P<field1>.*)/$', fun2)

note how the first url is tried first 注意如何首先尝试第一个URL

I would make it: 我会做到的:

url(r'^foobar/(?P<name>foo)/(?P<field1>.+)/$', views.foo),
url(r'^foobar/(?P<name>bar)/(?P<field1>.+)/$', views.bar),

Or: 要么:

url(r'^foobar/(?P<name>foo|bar)/(?P<field1>.+)/$', views.foo),

and: 和:

def foo(request, name, field1):
    if name = 'foo':
        do_foo(request, field1)
    else:
        do_bar(request, field1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM