我正在制作示例代码以使用表格和模型表格集。 create_function运行良好。但是update_function有问题。当它调用该函数时会发生错误MultiValueDictKeyError。我不知道该如何解决。请帮忙。
def update(request, portfolio_id):
template_name = 'portfolio_update_form.html'
pofol = Portfolio.objects.get(id=portfolio_id)
if request.method == 'GET':
form = PortfolioForm(instance=pofol)
formset = PortfolioImageModelFormSet(
queryset=PortfolioImage.objects.filter(portfolio__id=portfolio_id),
prefix='image'
)
elif request.method == 'POST':
form = PortfolioForm(request.POST, instance=pofol)
formset = PortfolioImageModelFormSet(request.POST, request.FILES, prefix='image')
if form.is_valid() and formset.is_valid():
portfolio = form.save()
for imageForm in formset:
pofolImage = imageForm.save(commit=False)
pofolImage.portfolio = portfolio
pofolImage.save()
return redirect('detail', portfolio_id)
return render(request, template_name, {
'form' : form,
'formset' : formset
})
forms.py
PortfolioImageModelFormSet = modelformset_factory(
PortfolioImage,
fields=('image','caption',),
widgets={'caption' : forms.TextInput(attrs={'class' : ''})},
labels={'caption': ''},
extra=1
)
答案 0 :(得分:0)
尝试类似这样的方法。您将必须创建Portfolio_update_form.html并定义您的创建视图your_create_view(请求,表单,模板)
def update(request, portfolio_id):
pofol = get_object_or_404(Portfolio, id=portfolio_id)
if request.method == 'POST':
form = PortfolioForm(request.POST, instance=pofol)
else:
form = PortfolioForm(instance=pofol)
return your_create_view(request, form, 'portfolio_update_form.html')