使用验证来防止重复的文件_name_被上传 [英] Use validation to prevent duplicate file _name_ being uploaded

查看:92
本文介绍了使用验证来防止重复的文件_name_被上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检测用户已提供要上传的文件的名称(通过 django.forms.ModelForm 使用 FileField 字段)与已存在的副本重复,因此决定对表单进行验证失败?

How can I detect that the name of a file that a user has provided for upload (via a django.forms.ModelForm using a FileField field) is a duplicate of one that exists, and thus decide to fail validation on the form?

I我发现这特别具有挑战性,因为从表单中,我看不到如何找到 upload_to 的值FileField ,因此我无法在文件系统中查看自己是否已经存在该文件。

I'm finding this particularly challenging, because from within the form, I don't see how I can find out what the value of upload_to is for this FileField, so I can't go looking myself in the file system to see if that file is there already.

推荐答案

如我所见,您有2个选择:

As i see it you have 2 options:

在您的 settings.py 来保存您的 upload_to,然后在进行验证时使用它来进行检查。
这样的事情可以验证(您需要更改您的upload_to ofc):

Set a value in your settings.py to hold your 'upload_to' and then use it to check when you are validating. Something like this to verify would work (you need to change your upload_to ofc):

from django.conf import settings

if settings.UPLOAD_TO:
    # Do something

问题在于您那里不能有子文件夹或任何复杂的文件。

Issue with that is that you can't have subfolders or anything complex there.

如您的评论所述,第二种选择是在您的目录中添加新列包含文件哈希值的模型。这种方法应该更好地工作。正如您的评论中提到的那样,为避免上载大文件,检查,失败,上载另一个大文件等,您可以尝试在客户端中对其进行散列并首先通过ajax对其进行验证(您将在服务器中再次对其进行验证,但这可以使您的用户运行得更快)。

A second option would be, as mentioned in your comments, to add a new column to your model that holds a hash for your file. This approach should work better. As someone mentioned in your comments, to avoid uploading a big file, checking, failing, uploading another big file, etc, you can try to hash it in the client and verify it via ajax first (you will verify it again in the server, but this can make things go faster for your users).

这篇关于使用验证来防止重复的文件_name_被上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆