整数的Django URL模式 [英] Django URL Pattern For Integer
问题描述
我是Python和Django的新手。我将URLPattern添加到urls.py中,如下所示:
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"),
我希望我的url接受参数可变长度的整数,例如db表的 id为0、100、1000、99999。但是我发现在上述模式中我只接受一位数字。如果我传递的不是整数而不是1位数字(例如999999),则会显示错误
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)/$']
我该如何构造URL模式,使程序从URL接受任意数量的数字整数?
How do I construct the URL Pattern that let the program accept any number of digits integer from URL?
推荐答案
RegEx应该具有 +
修饰符,例如
The RegEx should have +
modifier, like this
^address_edit/(\d+)/$
引用 Python的RegEx文档,
'+'
导致结果RE匹配先前RE的1个或多个重复。
ab +
将匹配a
,后跟任何非零数字的b
s;它不会只匹配a
。
'+'
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
将匹配任何数字( 0-9
)。但它只会匹配一次。要匹配两次,可以执行 \d\d
。但是随着接受位数的增加,您需要增加 \d
s的数目。但是RegEx有一种更简单的方法。如果您知道要接受的位数,则可以
\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}
这将接受三个连续的数字。如果要接受3到5位数字怎么办?正则表达式涵盖了这一点。
This will accept three consecutive numeric digits. What if you want to accept 3 to 5 digits? RegEx has that covered.
\d{3,5}
简单吧? :)现在,它将只接受3到5个数字(注意:小于3的任何内容也将不匹配)。现在,您要确保最小的1个数字,但最大的可以是任何数字。你会怎么做?只是将范围保持开放状态,像这样
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,}
现在,RegEx引擎将匹配最少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.
这篇关于整数的Django URL模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!