I have a form that enters data to db. I have another form with a drop down field that uses the data entered by the first form.
So when I submit data from the first form,the db is updated properly. But when I load the second form the drop down is not updated with the latest data.
Steps followed for debugging
The problem is not with transaction/commit etc. The query to retrieve the data for the drop down in second form is correct.
The problem is not with view cache either(cos we don't have any cache middleware) I also tried the cache decorators like @never_cahce,@cache_control etc
I tried giving a print statement in second form. I believe that the problem is with form cache. Every django form is loaded only once,ie. while loading the first page of the site. Afterwards the form is loaded from this cache.
First page
form
class AddOrganization(forms.Form):
orgList = getOrgUnitList()
orgUnit = forms.CharField(label=u'Organization Name',
max_length=50,
error_messages={'required':'Organization name is required field.'})
parentOrg= forms.ChoiceField(label=u'Parent Organization',
choices=[(u'Select',u'Select')]+orgList,
error_messages={'required':'Organization name is required field.'})
Second page
form
class AddUser(forms.Form):
orgUnitList = getOrgUnitList()
email = forms.EmailField(label=u'Email',
max_length=50,
error_messages={'required':'Email is required field'})
orgUnit = forms.ChoiceField(label=u'Organizational Unit',
choices=orgUnitList,
error_messages={'required':'Organizational unit is required field'})
Query
def getOrgUnitList():
orgUnitList = list(OrganizationUnit.objects.values_list('OrgUnitID','OrgUnitName').order_by('OrgUnitName'))
return orgUnitList
EDIT
Everything is just fine if I use modelforms.Why So?
The issue is the declaration of
orgUnitList
as a class property in the form. This means it's called once, when the form is originally defined. So no new elements will be seen, until the server process is restarted.One way to fix this would be to call the
getOrgUnitList
function inside the__init__
method of the form:Alternatively, you should look into using
ModelChoiceField
for orgUnit, as it deals with this sort of thing automatically.