我想更新一个可以有不同条目的表单集。我将能够呈现预先填充了正确数据的表单集,但是我做错了,因为它没有更新而是创建了一个新实例..
我看到了 inlineformset_factory但是因为我向表单集传递了多个值,所以我无法使用它..
如果有人有任何指示,我将不胜感激!
视图.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 })
表格.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
任何指针都会有很大帮助!
编辑
在凯瑟琳的一些建议之后
formset = ContactSet(request.POST, queryset=epis)
这给了我这个错误:
__init__() got an unexpected keyword argument 'queryset'
我尝试改变
from django.forms.models import modelformset_factory
ContactSet = modelformset_factory(Contact1Form, extra=len(epis), max_num=len(epis))
出现了这个错误:
'ModelFormOptions' object has no attribute 'many_to_many'
然后看到要解决这个错误,我需要改用模型的名称。
ContactSet = modelformset_factory(Contact, extra=len(epis), max_num=len(epis))
我得到一个 MultiValueDictKeyError