简体   繁体   中英

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?

PS 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 , and mycolor is a equence of non-digits , you can use

urlpatterns = [
    re_path(r'^products/((?P<my_color>)/)?(?P<my_year>)$', 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/<year>/'),
    path(r'^products/<color>/'),
    path(r'^products/<color>/<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, year):
    # …

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM