def generate_uuid_file_name(self, filename):
self.original_filename = filename
extension = filename.rsplit('.', 1)[1]
newfilename = uuid.uuid4().__str__() + '.' + extension
return self.directory() + newfilename
class FileUpload(models.Model):
original_filename = models.CharField(max_length=128)
fileobj = models.FileField(upload_to=generate_uuid_file_name)
On upload,
{"errors": {"original_filename": ["This field is required."]}, "success": false}
Adding blank=True, null=True to the FileUpload.original_filename allows the upload to succeed but does not save the original file name. On Django 1.5. According to this post, this should work.
By default, Django stores files locally, using the MEDIA_ROOT and MEDIA_URL settings. The examples below assume that you're using these defaults. However, Django provides ways to write custom file storage systems that allow you to completely customize where and how Django stores files.
FileField is a file-upload field. Before uploading files, one needs to specify a lot of settings so that file is securely saved and can be retrieved in a convenient manner. The default form widget for this field is a ClearableFileInput.
When Django handles a file upload, the file data ends up placed in request. FILES (for more on the request object see the documentation for request and response objects).
You can obtain such name with os. path. splitext [Python-doc] to split a filename in the "root" and the "extension". But you of course do not have access to that in the Django template.
Do that in the view (after null=True, blank=True are again part of your model):
file_object = UploadFileForm.save(commit=False)
file_object.original_filename = request.FILES['file'].name
file_object.save()
Mind that you will need to change the above code accordingly with your context etc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With