Django: inlineformset 'attribute has no file associated with it' 错误

Django: inlineformset 'attribute has no file associated with it' error

我有一个内联表单集,我可以一次上传一个模型的多个实例。你如何添加文件?我不断收到此错误消息“'document' 属性没有与之关联的文件。”

此处发生错误:if formset.is_valid():

型号 class答(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())

也将 request.FILES 添加到表单集中

formset = BFormSet(request.POST,request.FILES, instance=qs.first())