Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
上传文件django_Django_File_Uploading_Download - Fatal编程技术网

上传文件django

上传文件django,django,file,uploading,download,Django,File,Uploading,Download,我一直在看这个django片段: 我的代码是: 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(

我一直在看这个django片段:

我的代码是:

    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”的模型是否就是扩展的用户字段?另外,如何设置文件下载?我在文件里没有看到这方面的任何信息


谢谢。

查看Django的文档,了解模型的字段类型和Django表单字段类型

您可能需要定义一个模型来表示上载的文件:

#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/')

嗯,我会尝试一下,同时,我会在问号(保存的_文件变量)中添加什么。在这个例子中,他们使用了['thumbnail\u images','banner\u images']。但我不是在处理图像,我会把“word_document”之类的东西放进去吗?“键”字段的意义何在?键用于从中提取文件,正如链接所述,它们对应于模板上命名的输入字段。请注意,代码片段是在2008年提供的。上载路径和“上载到”字段必须相同吗?我这样问是因为我的实际路径会根据用户的用户名而改变。我不知道如何将用户名传递到模型类中。(与request.user类似,但这只发生在视图中。)我不知道你是如何定义
设置的。在你的应用程序中上载\u PATH
,但你应该输入什么取决于你设置的内容。你为什么认为上载Word文档与上载照片不同?