据我了解,您的问题不是如何动态生成此文件,而是创建一个供人们下载的链接...
我的建议如下:
0) 为您的文件创建一个模型,如果您想动态生成它,请不要使用 FileField,而只是生成此文件所需的信息:
class ZipStored(models.Model):
zip = FileField(upload_to="/choose/a/path/")
1) 创建并存储您的 Zip。这一步很重要,您在内存中创建 zip,然后将其转换为分配给 FileField:
function create_my_zip(request, [...]):
[...]
# This is a in-memory file
file_like = StringIO.StringIO()
# Create your zip, do all your stuff
zf = zipfile.ZipFile(file_like, mode='w')
[...]
# Your zip is saved in this "file"
zf.close()
file_like.seek(0)
# To store it we can use a InMemoryUploadedFile
inMemory = InMemoryUploadedFile(file_like, None, "my_zip_%s" % filename, 'application/zip', file_like.len, None)
zip = ZipStored(zip=inMemory)
# Your zip will be stored!
zip.save()
# Notify the user the zip was created or whatever
[...]
2)创建一个url,例如获取一个与id匹配的数字,也可以使用slugfield(this)
url(r'^get_my_zip/(\d+)$', "zippyApp.views.get_zip")
3) 现在的视图,这个视图会返回与url中传入的id匹配的文件,你也可以使用slug发送文本而不是id,并通过你的slugfield进行get过滤。
function get_zip(request, id):
myzip = ZipStored.object.get(pk = id)
filename = myzip.zip.name.split('/')[-1]
# You got the zip! Now, return it!
response = HttpResponse(myzip.file, content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=%s' % filename