2

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?

1
  • Are you actually saving the data when you process the form? That's usually done in the view. Plus you should probably be using formsets for this type of functionality. Commented Apr 21, 2015 at 13:40

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

It works perfectly! Cute logical solution, thank you very much! (Now I need to think how it works... :) )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.