Reputation: 87
I'm trying to develop a simple model form by Django to upload pdf files. The form is based on a model. Every time, user upload a file a database table entry would be created with the file path (including filename), uploaded user name and time Etc.
when I upload the same file again, Django is uploading the same file by altering its name (poster-proposal.pdf ->poster-proposal_IomFZQM.pdf). It is also creating another entry in the database table.
I want Django to give the user a warning when he is trying to upload an already existing file saying (a file with the same name is already existing) or something like that and not to upload the duplicate file.
I followed this post,post 1 but it says it does not prevent Django from uploading the file.
I followed this method post 2, but I'm new to Django and it seems complicated. I believe for newer Django versions there should be an easier way to address this issue.
I added unique = True to FileField.It did not work
models.py
class files(models.Model):
repo_id = models.ForeignKey(Repository, on_delete = models.CASCADE)
username = models.CharField(db_column='username',max_length = 45)
date = models.DateTimeField(auto_now_add=True, db_column = 'date')
file = models.FileField(upload_to='documents/', db_column = 'file', unique = True)
indicator_name =models.CharField(db_column = 'indicator_name',max_length = 100)
username = models.CharField(db_column='username',max_length = 45)
Any idea would be highly appreciated. Thanks
Upvotes: 1
Views: 2678
Reputation: 4208
The simplest way is to search for the name and then upload the file:
# Note that file name depends on your upload_to path.
# Either you should include it in the search or you have to use something like:
# filter(file_contains="filename") which might return results that you don't want
filename = "documents/" + filename_you_want_to_upload
files = files.objects.filter(file=filename)
if files.count() > 0:
# A file with that name exists.
# Return some error or ...
else:
# There is no file with that name.
# Upload the file and save it to database.
Upvotes: 2