discky
discky

Reputation: 15267

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.

Upvotes: 1

Views: 181

Answers (2)

Paulo Scardine
Paulo Scardine

Reputation: 77281

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)

Upvotes: 0

second
second

Reputation: 28637

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, e.g.:

 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

Upvotes: 1

Related Questions