Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving Original File Name in Django with FileField

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.

like image 376
Wade Williams Avatar asked Jun 28 '13 01:06

Wade Williams


People also ask

What is default file storage in Django?

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.

What is FileField in Django?

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.

Where does Django save uploaded files?

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

How can I get image name in Django?

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.


1 Answers

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

like image 162
Samuele Mattiuzzo Avatar answered Sep 27 '22 23:09

Samuele Mattiuzzo