Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do I Use A Decimal Number In A Django URL Pattern?

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

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?

like image 785
Jason Champion Avatar asked Jul 14 '09 23:07

Jason Champion


People also ask

How can we handle urls in Django?

Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL, matching against path_info . Once one of the URL patterns matches, Django imports and calls the given view, which is a Python function (or a class-based view).

What is Re_path in Django?

re_path is an implementation of the 'old' way of handling urls, which was previously (version <2) done by url from django. conf. urls . See the paragraph in Django 2.0 release notes about this.


1 Answers

It can be something like

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

url should not start with slash.

in views you can have function:

def byvalue(request,value='0.99'):
    try:
        value = float(value)
    except:
        ...
like image 165
Evgeny Avatar answered Sep 20 '22 18:09

Evgeny