简体   繁体   中英

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. 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(r'^foobar/(?P<field1>1)/$', fun1)
url(r'^foobar/(?P<field1>.*)/$', fun2)

note how the first url is tried first

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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