开发者

How to restrict values in a Django DecimalField?

I have an Order model with a price field. I'd like to have my form restrict this field to values between 0.0 and 1.0, but I don't want the actual model restricted as such.

Currently my form code is:

class OrderForm(ModelForm):
    class Meta:
        model = Order
        fields = ('stock', 'order', 'volume', 'price')

A dropdown input would be ideal, but I have no idea how to accomplish that through Django for开发者_StackOverflow社区ms.


class OrderForm(ModelForm):
    price = forms.ChoiceField(choices=PRICE_CHOICES)

Where PRICE_CHOICES is a tuple of tuples in the form of:

PRICE_CHOICES = (
    (value, display),
    (value, display),
    ...
)

Actually since you're dealing with a linear progression, you can even use some syntax sugar:

price_choices = [('%.2f' % (x*0.1), '$%.2f' % (x*0.1)) for x in range(0,11)]

The only difference is I threw a dollar sign in front of the display value, but you get the point.


The way I would do this is to, in my init method of the form modify the auto generated field by appending a validator to it that checks to see that the value of the form field is in the range you want.

Class OrderForm(forms.ModelForm):
   def __init__(*arg, **kwargs):
    super(OrderForm,self).__init__(*args, **kwargs)
    self.fields['price'].validators = [valid_price_range]


def valid_price_range(value):
    if value < 0 or value > 1:
       throw ValidationError(u'%s is not between 0 and 1' % value)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜