【问题标题】:Uploading files django上传文件 django
【发布时间】:2011-09-21 16:49:15
【问题描述】:

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

谢谢。

【问题讨论】:

  • 您认为上传 Word 文档与上传照片有何不同?

标签: django file uploading download


【解决方案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/')

【讨论】:

  • 嗯,我会试试这个,同时,我会在问号(save_file 变量)中输入什么。在示例中,他们使用了 ['thumbnail_images', 'banner_image']。但我不是在处理图像,我会放“word_document”之类的吗?无论如何,他们的“关键”领域有什么意义?
  • 这些键用于从Request.Files 中提取文件,正如该链接所说,它们对应于您在模板上为输入字段命名的任何内容。请注意,sn-p 是在 2008 年贡献的。
  • UPLOAD_PATH 和“upload_to”字段是否必须相同?我问这个是因为我的实际路径会根据用户的用户名而变化。而且我不知道如何将用户名传递给模型类。 (与 request.user 类似,只是只发生在视图中。)
  • 我不知道你是如何在你的应用程序中定义settings.UPLOAD_PATH的,但你应该在upload_to中添加什么取决于你将MEDIA_ROOT设置为什么。
猜你喜欢
  • 2013-03-27
  • 2011-07-31
  • 2011-03-18
  • 1970-01-01
  • 2013-05-08
  • 2011-06-27
  • 2016-03-11
  • 2017-01-18
  • 2023-03-24
相关资源
最近更新 更多