4

我还是 Django 的新手,并且已经找到了一些关于如何限制通过 Django 的 FileField 上传的文件类型的优秀 答案。但是,这些答案涉及单个文件上传的情况。我正在处理多个文件上传的情况,如下所示:

表格.py

from django.core.exceptions import ValidationError

class DocumentForm(forms.Form):
    def clean_docfile(self):
        file = self.cleaned_data["docfile"]

        if not file.name.endswith('.txt'):
            raise ValidationError(u'Error: Text files only.')

        return file

    docfile = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}),
                              label='Select some files'
                              )

模型.py

from django.db import models
from myproject.myapp.validators import validate_file_extension

class Document(models.Model):
    docfile = models.FileField(upload_to=_upload_path, validators = [validate_file_extension])

验证器.py

from django.core.exceptions import ValidationError

def validate_file_extension(value):
    if not value.name.endswith('.txt'):
        raise ValidationError(u'Error: Text files only.')

我希望用户能够一次上传多个文件,但如果至少一个文件的文件类型不正确,则所有文件都会被拒绝。

目前, clean_docfile 似乎只检查按字母顺序出现的最后文件的名称。因此,文件选择 [A.txt, B.txt, C.png] 不会上传(按预期),但 [A.txt, B.png, C.txt] 会上传(不应该上传)。当我在我的 clean_docfile 函数中查看对象 self.cleaned_data["docfile"] 的值时,它似乎只存储按字母顺序出现的文件的属性。如何恢复所有上传的文件名?

4

0 回答 0