我不太确定该怎么做,但是我的直觉是FileField不接受zip文件吗?尽管我已经了解到FieldField与文件类型无关,所以我不确定在这里出什么问题。
错误消息: AttributeError: 'ZipFile' object has no attribute '_committed'
Models.py
class UserDownloads(django.db.models.Model):
user = django.db.models.ForeignKey(
django.contrib.auth.models.User,
on_delete=django.db.models.CASCADE,
blank=True,
null=True,
)
file = django.db.models.FileField(storage=S3Storage())
Views.py
class DownloadZipFileView(LoginAndPermissionMixin, View):
permission_required = 'downloads.view_userdownloads'
def get(self, request, *args, **kwargs):
files = []
attachments = TaskAttachment.objects.\
order_by('-date_entered').\
filter(user=self.request.user).\
only('file')
for attachment in list(attachments):
obj = {'file_name': attachment.file.name, 'url': attachment.file.url}
files.append(obj)
zipped_file = get_zipped_file(files)
A = UserDownloads(file=zipped_file, user=self.request.user)
A.save()
get_zipped_file函数
def get_zipped_file(files, zip_subdir='attachments'):
zip_filename = zip_subdir + '.zip'
byte_stream = io.BytesIO()
zf = zipfile.ZipFile(byte_stream, 'w')
for file in files:
filename = file.get('file_name')
url = file.get('url')
file_response = requests.get(url)
if file_response.status_code == 200:
f1 = open(filename, 'wb')
f1.write(file_response.content)
f1.close()
fdir, fname = os.path.split(filename)
zip_path = os.path.join(zip_subdir, fname)
zf.write(filename, zip_path)
os.remove(fname)
zf.close()
return zf