在ModelForm

时间:2016-05-10 08:12:52

标签: python django django-forms

有两个模型,一个包含公司信息的主模型和一个将文件链接到公司模型的ForeignKey模型。我现在想在我的表单上集成一个MultiFileField,允许一次上传多个文件(使用django-multiupload)。

不幸的是,每当我发送表单时,我都会收到“此字段是必填项”。我的MultiFileField错误。

这是我的代码:

# models.py
class Company(models.Model):
    name = models.CharField(max_length=200)
    note = models.TextField()

class CompanyData(models.Model):
    company = models.ForeignKey(Company, on_delete=models.CASCADE)
    document = models.FileField(upload_to="attachments")

# forms.py
class CompanyForm(forms.ModelForm):

    attachments = MultiFileField(min_num=1, max_num=3, max_file_size=1024*1024*5)

    class Meta:
        model = Company
        fields = '__all__'

    def save(self, commit=True):
        instance = super(CompanyForm, self).save(commit)
        for each in self.cleaned_data['attachments']:
            CompanyData.objects.create(document=each, company=instance)
        return instance

# views.py
def company_edit(request, pk):
    current_company = get_object_or_404(Company, pk=pk)

    if request.method == "POST":
        form = CompanyForm(request.POST, instance=current_company)
        if form.is_valid():
            current_company = form.save(commit=False)
            current_company.save()
            return redirect('company_detail', pk=current_company.pk)
    else:
        form = CompanyForm(instance=current_company)

    contexts = {
        'form': form,
    }

    return render(request, 'company_edit.html', contexts)

# company_edit.html
  <form method="POST" class="post-form" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form }}
    <button type="submit" class="save">Save</button>
  </form>

1 个答案:

答案 0 :(得分:0)

如果同事django-newbies遇到类似的问题:我只是缺少request.FILES in

form = CompanyForm(request.POST, request.FILES, instance=current_company)