4SadMemeXD
4SadMemeXD

Reputation: 63

Urlpattern regular expression not working

So i'm trying to make url like so

re_path(r'^product_list/(?P<category_slug>[\w-]+)/(?:(?P<filters>[\w~@=]+)?)$', views.ProductListView.as_view(), name='filtered_product_list'),

and at this point it works with things like:

/product_list/sdasdadsad231/bruh=1~3~10@nobruh=1~4

bruh=1~3~10@nobruh=1~4 - those are filters

but later i want to implement search by word functionality

so i want it recognize things like

/product_list/sdasdadsad231/?filters=bruh-1~3~10&nobruh-1~4&search_for=athing

/product_list/sdasdadsad231/?filters=bruh-1~3~10&nobruh-1~4

/product_list/sdasdadsad231/?search_for=athing

/product_list/sdasdadsad231/

so in different situations it will get filters and/or search_for or nothing at all

Upvotes: 0

Views: 98

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477210

The part after the question mark is the query string [wiki] and does not belong to the path. Django will construct a QueryDict for this, and this will be available through request.GET [Django-doc]. Indeed, if the path is for example:

/product_list/sdasdadsad231/?filters=bruh-1~3~10&nobruh-1~4&search_for=athing

Then the ?filters=bruh-1~3~10&nobruh-1~4&search_for=athing is not part of the path, and it will be wrapped in request.GET as a QueryDict that looks like:

>>> QueryDict('filters=bruh-1~3~10&nobruh-1~4&search_for=athing')
<QueryDict: {'filters': ['bruh-1~3~10'], 'nobruh-1~4': [''], 'search_for': ['athing']}>

You thus can not capture the part after (and including) the question mark, this is already stripped of the path when trying to match with the re_path(…) and path(…) definitions.

Upvotes: 0

The fourth bird
The fourth bird

Reputation: 163467

You might write the pattern as:

^product_list/(?P<category_slug>[\w-]+)/(?:\??(?P<filters>[\w~@=&-]+)?)$

Regex demo

If you want to match the leading / from the example data, you can append that in the pattern after the ^

Upvotes: 1

Related Questions