Optional get parameters in django?

后端 未结 7 1648
后悔当初
后悔当初 2020-12-05 00:28

Can someone please explain how you can write a url pattern and view that allows optional parameters? I\'ve done this successfully, but I always break the url template tag.

7条回答
  •  臣服心动
    2020-12-05 01:01

    Others have demonstrated the way to handle this with two separate named URL patterns. If the repetition of part of the URL pattern bothers you, it's possible to get rid of it by using include():

    url(r'^so/(?P\d+)/', include('myapp.required_urls'))
    

    And then add a required_urls.py file with:

    url(r'^$', 'myapp.so', name='something')
    url(r'^(?P.+)/$', 'myapp.so', name='something_else')
    

    Normally I wouldn't consider this worth it unless there's a common prefix for quite a number of URLs (certainly more than two).

提交回复
热议问题