4๐
โ
If myyear
is a sequence of digits, and mycolor
is a equence of non-digits, you can use
urlpatterns = [
re_path(r'^products/((?P<my_color>\D+)/)?(?P<my_year>\d+)$', some_view),
]
this will pass an empty string for the corresponding elements if the my_color
or my_year
are not present. You thus can write a view that looks like:
def some_view(request, my_color, my_year):
if my_color:
# โฆ
if my_year:
# โฆ
If both have the same sequence of characters, this is not possible, since how would you interpret products/bla
? Is bla
the color, or the year?
That being said, I think you make it too complicated. You can define four patterns, for example:
urlpatterns = [
path(r'^products/', some_view),
path(r'^products/<int:year>/'),
path(r'^products/<str:color>/'),
path(r'^products/<str:color>/<int:year>/', some_view),
]
Here you thus define four views for the same view. The view can then define optional parameter:
def some_view(request, color=None, year=None):
# โฆ
Source:stackexchange.com