[Answer]-Django regex – optional grouped parameters

1👍

Create two url records for the same view:

url(r'^myapp/mytasks/$', myview.tasks, name='tasks'),
url(r'^myapp/mytasks/sort_by/(price_highest|price_lowest)/$', myview.tasks,
                                                   name='sorted_tasks'),

And then change the signature of the tasks() view to:

def tasks(request, sort_by=None):
    ...

In the template you can easily point to the both versions:

{% url 'tasks' %}
{% url 'sorted_tasks' 'price_highest' %}

UPDATE: If you really want to make the only one url record then the regex will be:

'^myapp/mytasks/(?:sort_by/(price_highest|price_lowest)/)?$'

But I am not sure that it will work with {% url %} tag.

Leave a comment