我有一个内联表单集,我可以一次上传一个模型的多个实例。您如何添加文件?我不断收到此错误消息“'文档'属性没有与之关联的文件。
错误在这里发生:if formset.is_valid():
型号 A类(models.Modle): 总计...
class B(models.Model):
invoice_id = models.ForeignKey(A)
misc_amt... = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)
document = models.FileField(upload_to='images/', blank=True)
如果添加此属性,则会收到其他错误:datastructures.MultiValueDictKeyError: "'b-0-id'"
@property
def document_url(self):
if self.document and hasattr(self.document, 'url'):
return self.document.url
表单集
BFormSet = inlineformset_factory(A, B,
extra=0,
widgets={
'misc_amt':forms.TextInput(attrs={'size': '6',}),
'document':forms.FileInput(attrs={'multiple': False}),
}
)
HTML
<form method="post" enctype="multipart/form-data">{% csrf_token %}
{{ b_form.management_form }}
<table class="table" >
<tr class="text-center">
<td><strong>Misc.</strong></td>
<td><strong>Document</strong></td>
</tr>
{% for form in getperinfo_form.forms %}
<tr class="text-center">
<td>${{ form.misc_amt }}</td>
<td>{{ form.document }}</td>
</tr>
{% endfor %}
</table>
</form>
views.py
class AUpdateView(LoginRequiredMixin, UpdateView):
model = B
form_class = BForm
template_name = 'A.html'
def post(self,request,*args,**kwargs):
self.object =None
form_class = self.get_form_class()
form = self.get_form(form_class)
qs = A.objects.filter(
...
)
formset = BFormSet(self.request.POST,instance=qs.first())
if formset.is_valid():
return self.form_valid(formset)
else:
return self.form_invalid(form,formset)
def form_valid(self,formset):
formset = formset.save(commit=False)
for i in formset:
i.save()
return HttpResponseRedirect(self.get_success_url())
答案 0 :(得分:1)
也将request.FILES
添加到表单集中
formset = BFormSet(request.POST,request.FILES, instance=qs.first())