Making a Regex Django URL Token Optional

前端 未结 2 358
余生分开走
余生分开走 2020-12-04 11:21

You have a URL which accepts a first_name and last_name in Django:

(\'^(?P[a-zA-Z]+)/(?P[a-zA-Z]         


        
相关标签:
2条回答
  • 2020-12-04 11:55
    ('^(?P<first_name>[a-zA-Z]+)/(?P<last_name>[a-zA-Z]+)(?:/(?P<title>[a-zA-Z]+))?/$','some_method'),
    

    Don't forget to give title a default value in the view.

    0 讨论(0)
  • 2020-12-04 11:56

    In case your are looking for multiple optional arguments, without any required ones, just omit "/" at the beginning, such as:

    re_path(r'^view(?:/(?P<dummy1>[a-zA-Z]+))?(?:/(?P<dummy2>[a-zA-Z]+))?(?:/(?P<dummy3>[a-zA-Z]+))?/$', views.MyView.as_view(), name='myname'),
    

    which you can browse at:

    http://localhost:8000/view/?dummy1=value1&dummy2=value2&dummy3=value3
    
    0 讨论(0)
提交回复
热议问题