, views.ad...">

Django integer url pattern

I am new to Python and Django. I added the URLPattern to urls.py as shown below:

url(r'^address_edit/(\d)/$', views.address_edit, name = "address_edit"), 

I want my url to accept a variable-length integer parameter, e.g. 0, 100, 1000, 99999, for the "id" of the db table. However, I found that I accept only one digit in the above pattern. If I pass an integer, not just 1 digit (e.g. 999999), this will result in 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 create a URL pattern that allows a program to accept any number of integer digits from a URL?

+6
source share
3 answers

RegEx should have a modifier + like this

 ^address_edit/(\d+)/$ 

Quote from Python RegEx Documentation ,

'+'

Makes the resulting RE match 1 or more repetitions of the previous RE. ab+ will match a followed by any nonzero b s; he will not only match a .

\d will match any numeric digit ( 0-9 ). But it will only match once. To combine it twice, you can either do \d\d . But as the number of digits to receive increases, you need to increase the number \d s. But RegEx has an easier way to do this. If you know the number of digits to accept, you can do

 \d{3} 

This will take three consecutive numeric digits. What if you want to accept 3 to 5 digits? RegEx has coverage.

 \d{3,5} 

Simple, yes? :) Now it will only accept 3 to 5 numeric digits (Note: anything less than 3 will also not match). Now you want to make sure that the minimum is 1 digital digit, but the maximum can be any. What would you do? Just leave the range open, like this

 \d{3,} 

Now the RegEx mechanism will correspond to a minimum of 3 digits, and the maximum can be any number. If you want to combine at least one digit and a maximum, there can be any number, then what would you do

 \d{1,} 

That's right :) Even that will work. But we have an abbreviation to do the same, + . As mentioned in the documentation, it will match any nonzero number of digits.

+15
source

In Django> = 2.0, this is done in a simpler and simpler way, as shown below.

 from django.urls import path from . import views urlpatterns = [ ... path('address_edit/<int:id>/', views.address_edit, name = "address_edit"), ... ] 
0
source

You can use django helper package Django Macros url

This allows you to set up URLs clean and fancy.

Your example will be

 address_edit/:id 

or

 address_edit/:address_id 
-1
source

All Articles