我一直在看这个django片段: http://djangosnippets.org/snippets/1036/#c3564
我的代码是:
def handle_uploads(request, key):
saved=[]
upload_dir = settings.UPLOAD_PATH % request.user.username
upload_full_path =os.path.join(settings.MEDIA_ROOT, upload_dir)
if not os.path.exists(upload_full_path):
os.makedirs(upload_full_path)
for key in keys:
if key in request.FILES:
upload = request.FILES[key]
while os.path.exists(os.path.join(upload_full_path, upload.name)):
if (request.user.username not in upload.name) and (request.user.first_name not in upload.name):
upload.name = request.user.username + "_" + upload.name
dest = open(os.path.join(upload_full_path, upload.name), 'wb')
for chunk in upload.chunks():
dest.write(chunk)
dest.close()
saved.append((key, os.path.join(upload_dir, upload.name)) )
return saved
def upload_view(request):
user = request.user
if user.is_authenticated():
if request.method == 'POST':
form =upload_form(request.POST, request.FILES)
if form.is_valid():
saved_file = handle_uploads(request, ?)
在给出的示例中,他们似乎上传了图片。如果我想上传ms word文档,我应该放在这里?同样在示例中,它们引用了一个名为MyModel()的模型,这个模型对于msword文档来说是什么样的。我希望我的网站工作的方式是每个用户都可以查看他们上传的文件。然后,如果他们需要,他们可以再次下载这些文件。要将文档归于每个用户,是否应该在扩展的user_field类中添加它?如果我这样做,示例中称为“MyModel”的模型是否只是扩展的用户字段?另外,如何设置文件下载?我没有在文档中看到任何关于此事的内容。
谢谢。
答案 0 :(得分:1)
查看Django的uploading files文档,模型的FileField字段类型和Django表单FileField字段类型。
您可能希望定义一个模型来表示您上传的文件:
#in your models file
from django.contrib.auth.models import User
class UploadedFile(models.Model):
user = models.ForeignKey(User)
file = models.FileField(upload_to='myfiles/')