1

I want to make my url to accept the optional parameters only when given. I am unable to make the parameters optional/non-capturing.


re_path(r'^users/(?:(?P<sort_by>\d+)/)?$', views.UserListView.as_view(), name='user_list'),

I want this url to accept a slug field only when provided to the view. How can I do this? It is showing an error

Reverse for 'user_list' with keyword arguments '{'sort_by': 'username'}' not found. 1 pattern(s) tried: ['admin/users/(?:(?P<sort_by>\\d+)/)?$']

when I passed sort_by='username'

Deshwal
  • 3,436
  • 4
  • 35
  • 94

2 Answers2

2

You could keep your url to:

re_path(r'^users/$', views.UserListView.as_view(), name='user_list'),

And then in your template use

   <a href="{% url 'user_list' %}?sort_by=username">Sort</a>
HenryM
  • 5,557
  • 7
  • 49
  • 105
  • Thanks a lot. It worked. Can you tell me how to sort data using that? It looks messy but yeah it is working. – Deshwal Aug 13 '19 at 14:34
0

I would create 2 URLs:

path('users/<str:sort_by>', views.UserListView.as_view(), name='user_list_by_user'),
path('users', views.UserListView.as_view(), {'sort_by': 'default_sort_you_use'}, name='user_list'),

Then you can call the appropriate URL and always have a sort_by value in the view.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Katty
  • 1
  • 3