Home > Enterprise >  Django: One url for multiple parameters
Django: One url for multiple parameters

Time:08-06

I am trying to implement a url that can handle multiple parameters. For example:

  • if i want to get the project with id 1 => project/1

  • if i want to get the project with id 2 => project/2

  • if i want to get the project with id 1 and 2 => project/1/2

  • if i want to get the project with id 1, 2, and 3 => project/1/2/3

Is there any way I could implement this logic without hard coding N urls for N possibilities?

CodePudding user response:

You could do it like this:

re_path(r'^project/(?P<id_list>[1-9][0-9]*(?:/[1-9][0-9] )*)$', your_view),

and then in your view split the id list again:

ids = id_list.split('/')

CodePudding user response:

You can have multiple URLS using the sane view, and once the view starts they can interrogate their own kwargs.

path('project/<first:int>/<second:int>/<third:int/', MyView.as_view(), name='project_3args'),
path('project/<first:int>/<second:int>/', MyView.as_view(), name='project_2args'),
path('project/<first:int>/', MyView.as_view(), name='project_1arg'),

(The order may matter, put the longest first. Have never done this)

In the view, something like

third = self.kwargs.get('third', None)
if third:
    # process 3-arg form

You do need one url for each number of arguments.

Alternatively there's nothing wrong with Boldewyn's use of re_path if you want just one argument that's a slash-separated list with no (small) limit on how many items.

Finally there's also request.GET if you decide to use something like

/project_foo/?item=1&item=47&item=97

request.Get.getlist('item') will return ['1','47','97']. GET Querystrings are the most general, in that absolutely anything can be supplied in bite-sized pieces this way.

  • Related