我试图弄清楚如何处理Django中的文件字段中的多个文件。我已经想出如何将“multiple”属性添加到表单字段。我现在需要做的是遍历每个文件并执行一些逻辑。
我有一个包含这样字段的表单(在views.py中):
class RecipientListForm(forms.Form):
name = forms.CharField()
recipients = forms.CharField(
required=False,
widget=forms.Textarea(attrs={'placeholder':"James Jameson, james.jameson@aol.com"}),
label="Paste recipient information (comma-separated, in 'name, email' format)")
recipients_file = RecipientsFileField(
required=False,
widget=forms.FileInput(attrs={'multiple':"true"}),
label="Or upload a .csv file in 'name, email' format (max size %dMB)" % RecipientsFileField.MAX_FILESIZE_MB)
def __init__(self, account, recipient_list=None, *args, **kwargs):
super(RecipientListForm, self).__init__(*args, **kwargs)
self.account = account
self.recipient_list = recipient_list
def clean(self, *args, **kwargs):
...
RecipientsFileField看起来像这样(也在views.py中):
class RecipientsFileField(forms.FileField):
MAX_FILESIZE_MB = 30
def validate(self, value):
super(RecipientsFileField, self).validate(value)
if not value: return
fname = value.name
if (value.content_type not in (('text/csv',) + EXCEL_MIMETYPES) or not re.search(r'\.(xlsx?|csv)$', fname, re.I)):
raise forms.ValidationError('Please upload a .csv or .xlsx file')
if value.size >= self.MAX_FILESIZE_MB * 1024 * 1024:
raise forms.ValidationError('File must be less than %dMB' % (self.MAX_FILESIZE_MB,))
我试图在clean
的{{1}}方法中执行我的逻辑,但我只能访问上传的第一个文件,似乎没有上传其他文件。我查看了文档,但这些表单的设置方式似乎没有反映在有关表单的文档中,除非我只是在错误的地方查找。提前致谢!
答案 0 :(得分:1)
根据this section of the Django docs,您应该能够通过以下方式从请求对象获取文件:
files = request.FILES.getlist('recipients_file')
希望这有帮助。