Django URL Pattern For Integer

随声附和 提交于 2019-12-01 16:52:15

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 match a followed by any non-zero number of bs; it will not match just a.

\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 \ds. 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.

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"),
    ...
]

You can use my django helper package Django Macros URL

This allow you have urls configuration clean and fancy.

Your example will be

address_edit/:id

or

address_edit/:address_id
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!