How to allow different select choices based on model attribute value ?

I have a small SHOP with up to 20 products.
Currently I have hardcoded the maximum quantity per item in form CartAddProductForm - for each item allowed quantity choice is up to 10 - see the code below:

PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 11)]

class CartAddProductForm(forms.Form):
    quantity = forms.TypedChoiceField(
                                label = '',
                                widget=forms.Select(attrs={'class': 'quantity'}),
    override = forms.BooleanField(required=False,

Additionally I defined max_quantity attribute in the Product model.
How should I define my form to allow different choices per product ?


Some of the specifics will depend upon when and how you’re creating an instance of this form, but you can change the field attributes of a form after it has been created but before it’s rendered.

For example, you could do something like:

my_form = CartAddProductForm(...)
my_form.fields['quantity'].choices = get_choices_for_form(...)

where get_choices_for_form is a method you write to return the proper list.

1 Like