Search code examples
pythondjangodjango-2.2

How to pass multi optional URL parameters in django?


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 (?)


Solution

  • 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):
        # …