50

python – 如何在Django URL模式中使用十进制数?

 5 years ago
source link: https://codeday.me/bug/20190112/511032.html?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

我想在Django URL模式中使用带小数点的数字,但我不确定它是否真的可行(我不是正则表达式专家).

这是我想要用于URL的内容:

/item/value/0.01
/item/value/0.05

这些网址会显示价值0.01美元或0.05美元的商品.当然,我可以采取简单的方法,并以美分传递值,因此它将是/ item / value / 1,但我希望在我的视图中接收作为十进制数据类型而不是整数的参数(和我可能不得不在某个时候处理一小部分分数).是否可以在Django URL模式中编写一个可以处理此问题的正则表达式?

它可以是类似的东西

urlpatterns = patterns('',
   (r'^item/value/(?P<value>\d+\.\d{2})/$', 'myapp.views.byvalue'),
   ... more urls
)

url不应该以斜线开头.

在视图中你可以有功能:

def byvalue(request,value='0.99'):
    try:
        value = float(value)
    except:
        ...

翻译自:https://stackoverflow.com/questions/1128693/how-do-i-use-a-decimal-number-in-a-django-url-pattern


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK