上传文件django



我一直在看这个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, ?)

在给出的例子中,他们似乎上传了图像。如果我想上传msword文档,我应该在这里放什么?同样在这个例子中,他们引用了一个名为MyModel()的模型,这个模型对于msword文档来说是什么样子的。我希望我的网站工作的方式是每个用户都可以查看他们上传的文档。然后,如果需要,他们可以再次下载这些文档。要将文档属性为每个用户,我应该将其添加到扩展的user_field类中吗?如果我这样做了,示例中被称为"MyModel"的模型会只是扩展的用户字段吗?此外,如何设置文件下载?我在文件中没有看到任何关于这件事的信息。

谢谢。

查看Django上传文件的文档、模型的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/')

相关内容

  • 没有找到相关文章

最新更新