I'm new to Python and Django. I added a URLPattern into urls.py as below:
url(r'^address_edit/(\d)/$', views.address_edit, name = "address_edit"),
I want my url accept a parameter of an integer with variable length, E.g. 0, 100, 1000, 99999, for the "id" of a db table. However I found that I only accept only one digits in above pattern. If i pass a integer not 1 digit only (e.g. 999999), it show an error
Reverse for 'address_edit' with arguments '(9999999,)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['address_book/address_edit/(\\d)/$']
How do I construct the URL Pattern that let the program accept any number of digits integer from URL?
In Django >= 2.0 version, this is done in a more cleaner and simpler way like below.
from django.urls import path
from . import views
urlpatterns = [
...
path('address_edit/<int:id>/', views.address_edit, name = "address_edit"),
...
]
The RegEx should have +
modifier, like this
^address_edit/(\d+)/$
Quoting from Python's RegEx documentation,
'+'
Causes the resulting RE to match 1 or more repetitions of the preceding RE.
ab+
will matcha
followed by any non-zero number ofb
s; it will not match justa
.
\d
will match any numeric digit (0-9
). But it will match only once. To match it twice, you can either do \d\d
. But as the number of digits to accept grows, you need to increase the number of \d
s. But RegEx has a simpler way to do it. If you know the number of digits to accept then you can do
\d{3}
This will accept three consecutive numeric digits. What if you want to accept 3 to 5 digits? RegEx has that covered.
\d{3,5}
Simple, huh? :) Now, it will accept only 3 to 5 numeric digits (Note: Anything lesser than 3 also will not be matched). Now, you want to make sure that minimum 1 numeric digit, but maximum can be anything. What would you do? Just leave the range open ended, like this
\d{3,}
Now, RegEx engine will match minimum of 3 digits and maximum can be any number. If you want to match minimum one digit and maximum can be any number, then what would you do
\d{1,}
Correct :) Even this will work. But we have a shorthand notation to do the same, +
. As mentioned on the documentation, it will match any non-zero number of digits.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With