views:

133

answers:

1

Hello, I want to develop a basic quantity widget that is a dropdown selection box, consuming an integer which will be the maximum amount of quantity, users can select from 1 to the maximum quantity.

And in the end my form will be using this widget and if somehow the given amount is greater than the maximum, it shouldn't validate. (indeed regular users won't be able to select more than maximum but I guess it can be tried by sending direct request to the server.)

How can this be done?

Thanks

edit: I think it can be something like this to begin with, however I want my field to be a select(from 1 to max maximum quantity), not textinput field.

def quantity_field(quantity=1):
    class QuantityForm(forms.Form):
        forms.IntegerField(label="Purchase quantity",min_value=1,max_value=quantity,required=True,widget=forms.Select)
    return QuantityForm
+2  A: 

Ok I have done it:

def purchase_form(quantity=1):
    class QuantityForm(forms.Form):
        forms.IntegerField(label="Purchase quantity",min_value=1,max_value=quantity,required=True,widget=forms.Select(choices=  [ (i,i) for i in range(1,quantity+1) ]) )
    return QuantityForm

output for purchase_form(10):

>>>print d
<tr><th>Purchase quantity:</th><td><select name="x">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select></td></tr>

also validates:

>>> d.clean(5)
5
>>> d.clean(11)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/local/lib/python2.6/dist-packages/django/forms/fields.py", line 187, in clean
    raise ValidationError(self.error_messages['max_value'] % self.max_value)
ValidationError: [u'Ensure this value is less than or equal to 10.']
Hellnar