Sunday, March 31, 2013

Re: how do I specify optional params in url?

Al 31/03/13 19:00, En/na frocco ha escrit:
> Hello,
>
> Here is my current url.
>
> url(r'^narrow_category/(\d+)/(\w*)/(\d*)/(\d*)/(\d*)/$',
> 'catalog.views.narrow_category', name="narrow_category"),
>
> d+ is required
> w* can be optional
> last three d* can be optional
>
> This setting is not working.

You should be a bit more explicit about what "is not working" means.

I presume that you expect that an URL like "narrow_category/23" should
be matched against your url definition. No, it won't, since the slashes
are not optional. All those will match against your regular expression:

narrow_category/23/////
narrow_category/23/foo////
narrow_category/23/45////
narrow_category/23///23//

I think that the cleanest solution is defining a set of urls and,
somehow, provide default values for the missing parts:

def my_view(request, foo, bar="spam", baz=1234):
pass

url(r"^narrow/(\d+)/$", views.my_view, ...)
url(r"^narrow/(\d+)/(\w+)/$", views.my_view, ...)
url(r"^narrow/(\d+)/(\w+)/(\d+)/$", views.my_view, ...)

Note that the parts are no longer optional (+ instead of *).

It works like this:

/narrow/23/
matches the 1st rule
django calls: my_view(request, "23")
the view gets the arguments: foo="23", bar="spam", baz=1234

/narrow/23/baz/
2nd rule
my_view(request, "23", "baz")
foo="23", bar="baz", baz=1234

/narrow/23/baz/45/
3rd rule
my_view(request, "23", "baz", "45")
foo="23", bar="baz", baz="45"

/narrow/23/45/
2nd rule
my_view(request, "23", "45")
foo="23", bar="45", baz=1234


HTH

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.

No comments:

Post a Comment