Richard
Richard

Reputation: 65540

Django: append URL parameters to a list?

I currently have URLs of the form /blue - each URL is a colour. The associated URL pattern is as follows:

 (r'^(?P<colour>\w+)$', 'views.colour')

I'm wondering if it's possible to have URLs that look like a natural language list, of indeterminate length, separated by -or-:

/blue-or-green-or-yellow

Ideally the associated URL pattern would append each match to a Python list, ready to be handled in the view:

 (r'^(?P<colour_list>\w+)(?:-or-(?P<colour_list>\w+))+$', 'views.colour')

Is there any way to do this in Django?

Upvotes: 1

Views: 1610

Answers (3)

Aamir Rind
Aamir Rind

Reputation: 39659

Something like this will help:

takes comma separated colours

(r'^(?P<colours>[\w,]+)$', 'views.colour')

then in view:

colours = colours.split(',')

Upvotes: 0

Ria
Ria

Reputation: 10347

Try this regex:

(\w+(?:-or-)?)+

or use string split:

result = colours.split("-or-")

Upvotes: 0

DanielB
DanielB

Reputation: 2958

Something like (?P<colour_list>(\w+(\-or\-)?)+) will get the entire substring match, then you can just split by -or-

Note, however, that then blue-or- would be valid match, so you may want to split it like this: filter(bool, colour_list.split('-or-'))

Upvotes: 4

Related Questions