[Answered ]-Use validation to prevent duplicate file _name_ being uploaded

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

1👍

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

👤paul

Leave a comment