views:

464

answers:

3

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?

+8  A: 

I don't know about Django specifically, but this should match the URL:

r"^/item/value/(\d+\.\d+)$"
harto
If you want to have ints and floats in *one* url, write something like this: `r"^/item/value/(\d+(?:\.\d+))$"`
Boldewyn
+7  A: 

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:
        ...
Evgeny
+2  A: 

If the values to be accepted are only $0.01 or $0.05, the harto's pattern may be specified like this:

r"^/item/value/(\d\.\d{2})$"
TonyCool
Thank you, each post added a little piece of the puzzle. Evgeny had the magic bullet.
Jason Champion