【问题标题】:django formset - not able to update entriesdjango formset - 无法更新条目
【发布时间】:2023-03-08 05:59:01
【问题描述】:

我想更新一个可以有不同条目的表单集。我将能够呈现预先填充了正确数据的表单集,但是我做错了,因为它没有更新而是创建了一个新实例..

我看到 inlineformset_factory 但是因为我向表单集传递了多个值,所以我无法使用它..

如果有人有任何指点,我将不胜感激!

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

任何指针都会有很大帮助!

编辑

根据凯瑟琳的一些建议

  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

【问题讨论】:

    标签: django django-forms


    【解决方案1】:

    您只是忘记在表单集中添加instance

     if request.method =='POST':
        formset = ContactSet(request.POST, queryset=epis)
        if formset.is_valid():
    

    【讨论】:

    • 但是 epis 是一个对象列表。我想我只需要将一个对象传递给实例
    • 我不知道哪个对象连接到您的 ContactSet 表单,这就是我猜测它是 epis 的原因。但这里的重点是你忘了加上instance 等于你要更新的对象
    • 但我正在使用 formset,因为我想更新几个对象。 epis 可能是这样的:[, , , ],它将显示 4 种不同的表格以及这些联系人的信息。我的问题是,当我提交它时,它会创建一个新对象而不是更新。我已经尝试过你的建议,但它给了我这个错误:__init__() got an unexpected keyword argument 'instance'
    • 对不起,我忘了你使用 formset。将其替换为queryset。答案已更新
    • 我已经尝试过您的解决方案,但我仍在处理一些错误。你能看看我的编辑吗?如果你知道如何解决这个问题。谢谢
    【解决方案2】:
    MyFormSet = modelformset_factory(ModelName, form=MyForm)
    qs = ModelName.objects.filter(user=request.user)
    formset = MyFormSet(queryset=qs)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-17
      • 2023-03-08
      • 2020-05-08
      • 2019-11-27
      相关资源
      最近更新 更多