gpt4 book ai didi

python - 更新内联表单集时出现 MultiValueDictKeyError

转载 作者:太空宇宙 更新时间:2023-11-04 01:05:56 24 4
gpt4 key购买 nike

我在更新内联表单集时遇到 Django 问题。我想更新一个表单和一个内联表单集,但它引发了这个错误:

"MultiValueDictKeyError"

Exception Value: "u'clientphone_set-0-id'"

这是我的观点:

def edit_client(request, client_id):

client_to_edit = Client.objects.get(id=client_id)
form = ClientForm(instance=client_to_edit)
phone_formset = ClientPhoneFormSet(instance=client_to_edit)

if request.method == 'POST':
form = ClientForm(request.POST, instance=client_to_edit)

if form.is_valid():
form_saved = form.save(commit=False)
phone_formset = ClientPhoneFormSet(request.POST, request.FILES, instance=form_saved)

if phone_formset.is_valid():
form_saved.save()
phone_formset.save()
return client(request)

return render(request, 'WorkOrders/add_client.html', {'form' : form, 'phone_formset' : phone_formset})

这是我的表格

class ClientForm(forms.ModelForm):
name = forms.CharField(max_length=128)
rif = forms.CharField(max_length=10)
address = forms.CharField(max_length=250)

class Meta:
model = Client
fields = ('name','rif','address',)

ClientPhoneFormSet = inlineformset_factory(Client, ClientPhone, extra=1, fields=('phone_number',), can_delete=True)

这是我的模板

<form class="form-horizontal" id="add_client" method="post" action=".">
{% csrf_token %}
{% for field in form.visible_fields %}
<div class="form-group">
<label for="{{ field.id }}" class="col-sm-2 control-label">{{ field.help_text }}</label>
<div class="col-sm-10">
{{ field.errors }}
{{ field }}
</div>
</div>
{% endfor %}
<div class="form-group">
<label for="{{ field.id }}" class="col-sm-2 control-label">Teléfono</label>
<div class="col-sm-10">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
{% for form in phone_formset.forms %}
<tr>
<td>
{% if form.instance.pk %}
{{ form.DELETE }}
{% endif %}
{{ form.errors }}
{{ form.phone_number }}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{{ phone_formset.management_form }}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary">Guardar</button>
<a href="{% url 'index' %}" class="btn btn-primary">Volver</a>
</div>
</div>
</div>
</form>

它打开表单没有问题,但在我提交时发生错误。

谢谢。

最佳答案

我通过使用 phone_formset 而不是 phone_formset.forms 修复了它,并添加了 {{ phone_field.id }}

结果如下:

<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
{% for phone_field in phone_formset %}
<tr>
<td>
{% if phone_field.instance.pk %}
{{ phone_field.DELETE }}
{% endif %}
{{ phone_field.errors }}
{{ phone_field.id }}
{{ phone_field.phone_number }}
</td>
</tr>
{% endfor %}
</tbody>
</table>

关于python - 更新内联表单集时出现 MultiValueDictKeyError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30446162/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com