'1 always not match in Django re_path regular expression
I try to create a dynamic path which accepts either null or positive integer.
For example:
http://127.0.0.1:8000/my_url/23
in url.py:
from django.urls import path, re_path
urlpatterns = [
re_path(r'^my_url/(\s*|[0-9]{0,})$', views.my_function, name='my_function'),
]
in view.py:
def my_function(request, my_id):
if my_id == '':
#Do somthing
else:
#Do another somthing
Strange thing is:
followings passed in my test:
http://127.0.0.1:8000/my_url/2
http://127.0.0.1:8000/my_url/10
The only one that failed (meaning return to 404, no url found) is:
http://127.0.0.1:8000/my_url/1
why only '1' does not match? Is 1 treated specially in re_path function?
/****** Update ******/
It turns out that there is simply something wrong with my browser (might be a cookie issue). After I clean up and restart my browser, the regular expression works for 1 as well.
Solution 1:[1]
The update on your question explains that this is likely some caching mechanism in the browser.
I would however advise to split this up into two paths: one with an <int:my_int> parameter, and one without such parameter. These can both call the same view:
from django.urls import path
urlpatterns = [
path('my_url/', views.my_function, name='my_function'),
path('my_url/<int:my_id>/', views.my_function, name='my_function')
]
In the view, you then make my_id an optional parameter that resolves to None in case it is not called with this parameter:
def my_function(request, my_id=None):
if my_id is None:
# do something
else:
# do something else
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Willem Van Onsem |
