Django form reload data

I have a form that enters data in db. I have another form with a drop down field that uses the data entered by the first form.

Therefore, when I submit data from the first form, db is updated properly. But when I load the second form, the dropdown menu is not updated with the latest data.

Completed steps for debugging

The problem is not in transaction / commit, etc. The data request for the drop-down list in the second form is correct.

The problem is not the presentation cache (since we don't have cache middleware) I also tried cache decoders like @never_cahce, @cache_control, etc.

I tried to give a print statement in the second form. I believe the problem is with the form cache. Each django form is loaded only once, i.e. when loading the first page of the site. After that, the form is loaded from this cache.

First page

The 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

The 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?

+6
source share
1 answer

The problem is declaring orgUnitList as a class property on the form. This means that it is called once when the form is initially defined. Therefore, no new items will be visible until the server process is restarted.

One way to fix this is to call the getOrgUnitList function inside the form's __init__ method:

 class AddOrganization(forms.Form): ... def __init__(self, *args, **kwargs): super(AddOrganizationForm, self).__init__(*args, **kwargs) self.fields['orgUnit'].choices = getOrgUnitList() 

Alternatively, you should study ModelChoiceField for orgUnit as it deals with this view automatically.

+6
source

Source: https://habr.com/ru/post/903658/


All Articles