0

我一直在看这个 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”的模型是否只是扩展的用户字段?另外,如何设置文件下载?我在文档中没有看到任何关于此的内容。

谢谢你。

4

1 回答 1

1

查看 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/')
于 2011-06-24T02:19:44.037 回答