如何在Django网址格式中使用十进制数? [英] How Do I Use A Decimal Number In A Django URL Pattern?
问题描述
我想在Django网址格式中使用一个带小数点的数字,但我不确定是否可以(我不是正则表达式专家)。
I'd like to use a number with a decimal point in a Django URL pattern but I'm not sure whether it's actually possible (I'm not a regex expert).
以下是我要用于网址的内容:
Here's what I want to use for URLs:
/item/value/0.01
/item/value/0.05
这些网址将显示价值为0.01美元或0.05美元的项目。当然,我可以采取简单的方法,并通过价值在美分,所以它将是/ item / value / 1,但我想接收在我的视图中的参数作为十进制数据类型而不是一个整数(和某些时候我可能需要处理一分钟的分数)。可以在一个Django URL模式中编写一个正则表达式来处理这个问题?
Those URLs would show items valued at $0.01 or $0.05. Sure, I could take the easy way out and pass the value in cents so it would be /item/value/1, but I'd like to receive the argument in my view as a decimal data type rather than as an integer (and I may have to deal with fractions of a cent at some point). Is it possible to write a regex in a Django URL pattern that will handle this?
推荐答案
它可以像
urlpatterns = patterns('',
(r'^item/value/(?P<value>\d+\.\d{2})/$', 'myapp.views.byvalue'),
... more urls
)
url不应该以斜杠开头。
url should not start with slash.
在视图中你可以有功能:
in views you can have function:
def byvalue(request,value='0.99'):
try:
value = float(value)
except:
...
这篇关于如何在Django网址格式中使用十进制数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!