I want to update a formset that can have different entries. I will able to present the formset pre populated with the correct data, however I'm doing something wrong since it does not update but creates a new instance..
I'm seen inlineformset_factory however since I'm passing more than one value to the formset I was not able to work with it..
If anyone has any pointer I will truly appreciate it!
views.py
epis = Contact.objects.filter(episode=int(value))
ContactSet = formset_factory(Contact1Form, extra=len(epis), max_num=len(epis))
if request.method =='POST':
formset = ContactSet(request.POST)
if formset.is_valid():
for form in formset.forms:
age = form.cleaned_data['age']
bcg = form.cleaned_data['bcg_scar']
radio = form.cleaned_data['radiology']
profile = form.save(commit=False)
for i in epis:
profile.contact = i
fields = {'age': age, 'bcg_scar': bcg, 'radiology': radio}
for key, value in fields.items():
if value == u'':
setattr(profile, key, None)
else:
setattr(profile, key, value)
profile.save()
return render_to_response('success.html', {'location': location})
else:
dic = []
for c in epis:
aux = {}
for f in c._meta.fields:
if f.name not in ['contact_id', 'episode']:
aux[f.name] = getattr(c, f.name)
dic.append(aux)
formset = ContactSet(initial=dic)
return render_to_response('form.html',
{ 'msg': msg,
'location': location,
'formset': formset,
'word': word })
forms.py
class ContactForm(forms.ModelForm):
affinity = forms.ModelChoiceField(queryset=Affinity.objects.all(),
label=ugettext("Affinity"))
age = forms.IntegerField(label=ugettext("Age when diagnosed"),
required=False)
MAYBECHOICES = (
('', '---------'),
(ugettext('Yes'), ugettext('Yes')),
(ugettext('No'), ugettext('No')))
bcg_scar = forms.ChoiceField(choices=MAYBECHOICES, label=ugettext(
"BCG scar"), required=False)
radiology = forms.ModelChoiceField(queryset=Radiology.objects.all(),
label=ugettext("Radiology"),required=False)
class Meta:
model = Contact
Any pointers would be of great help!
EDIT
After some suggestions from Catherine
formset = ContactSet(request.POST, queryset=epis)
which gave me this error:
__init__() got an unexpected keyword argument 'queryset'
I try changing
from django.forms.models import modelformset_factory
ContactSet = modelformset_factory(Contact1Form, extra=len(epis), max_num=len(epis))
and this error appeared:
'ModelFormOptions' object has no attribute 'many_to_many'
and then saw that to solve this error I will need to use the name of the model instead.
ContactSet = modelformset_factory(Contact, extra=len(epis), max_num=len(epis))
and I get a MultiValueDictKeyError