GreenAsJade
GreenAsJade

Reputation: 14685

Use validation to prevent duplicate file _name_ being uploaded

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.

Upvotes: 1

Views: 2024

Answers (2)

paul
paul

Reputation: 1142

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

Upvotes: 1

cdvv7788
cdvv7788

Reputation: 2089

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

Upvotes: 1

Related Questions