Use validation to prevent duplicate file _name_ being uploaded

♀尐吖头ヾ 提交于 2019-12-23 02:57:20

问题


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'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.


回答1:


As i see it you have 2 options:

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.

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).




回答2:


Older question, but Django 1.11 now supports the unique option on FileField. Set unique=True on your field declaration on your model.

It shouldn't matter what you are setting upload_to to. The file name will still be stored in the database.

Changed in Django 1.11: In older versions, unique=True can’t be used on FileField.

https://docs.djangoproject.com/en/1.11/ref/models/fields/#unique



来源:https://stackoverflow.com/questions/27227716/use-validation-to-prevent-duplicate-file-name-being-uploaded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!