How to pass multi optional URL parameters?
For example I want pass 2 params: my_color
and my_year
, but they are optional, so may be none of them will be passed, may be both, or may be only one.
Currently in urls.py
I have :
urlpatterns = [
re_path(r'^products/(?P<my_color>.*)/(?P<my_year>.*)$', some_view),
]
This obviously is not correct and works only if both of them are passed.
What would be correct solution?
P.S. I found answers when only one optional parameter needs to be pass, but not figured out how to do same for few parameters. Also it seems "multiple-routes option" is not solution in this case (?)
If
myyear
is a sequence of digits, andmycolor
is a equence of non-digits, you can usethis will pass an empty string for the corresponding elements if the
my_color
ormy_year
are not present. You thus can write a view that looks like:If both have the same sequence of characters, this is not possible, since how would you interpret
products/bla
? Isbla
the color, or the year?That being said, I think you make it too complicated. You can define four patterns, for example:
Here you thus define four views for the same view. The view can then define optional parameter: