Reputation: 35
I have a Django form that generates input "number" fields from values of database with storehouse items. After processing all the input data is stored in a temporary database. Because of that, the values of the main storehouse database (like amount of product) change each time. The main problem is that after all these steps, the form does not update (for exmaple: maximum input value). Update form is possible only when the server is restarted.
My form class definition looks like: (for each iteration, loop creates a new variable (input field name) and defines maximum and minimum input value.)
class StorehouseItems(forms.Form):
items = Storehouse.objects.all()
for key in items:
locals()[key.id] = forms.IntegerField(label=key.name+"<br />(max "+str(key.amount)+" "+key.prefix+")",
min_value=0, max_value=key.amount, required=False)
What am I doing wrong?
Upvotes: 2
Views: 1862
Reputation: 45565
You should add fields in the __init__()
method of a form:
class StorehouseItems(forms.Form):
def __init__(self, *args, **kwargs):
super(StorehouseItems, self).__init__(*args, **kwargs)
for key in Storehouse.objects.all():
field = str(key.pk)
label = "%s<br />(max %s%s)" % (key.name, key.amount, key.prefix)
self.fields[field] = forms.IntegerField(label=label,
min_value=0,
max_value=key.amount,
required=False)
Upvotes: 2