Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choose the filename of an uploaded file with Django

I'm uploading images (represented by a FileField) and I need to rename those files when they are uploaded.

I want them to be formated like that:

"%d-%d-%s.%s" % (width, height, md5hash, original_extension)

I've read the documentation but I don't know if I need to write my own FileSystemStorage class or my own FileField class or ... ? Everything is so linked I don't know where to start.

like image 550
knarf Avatar asked Aug 06 '09 08:08

knarf


People also ask

Where does Django save uploaded files?

MEDIA_ROOT It takes in the absolute file path of a directory. We have used the same join functions in Django static files tutorial that we have passed in the file path of media directory. This directory will store all the files a user uploads in Django. Although you can directly give the path as a string in MEDIA_ROOT.

What are the two required form attributes for Django file uploads?

Go to your HTML template and add a <form> element. Add the attributes method="post" and enctype="multipart/form-data" . POST is used to send the data to the server while enctype specifies how the form-data should be encoded when sent to the server. Both of these attributes are required to post file uploads.

What is SimpleUploadedFile?

class SimpleUploadedFile(InMemoryUploadedFile): """ A simple representation of a file, which just has content, size, and a name. """ def __init__(self, name, content, content_type="text/plain"): content = content or b"" super().


1 Answers

You don't need to write your own FileStorage class or anything that complicated.

The 'upload_to' parameter on File/ImageFields can take a function that returns the path/file to use.

How to do this has already been answered here

like image 165
arcanum Avatar answered Sep 30 '22 02:09

arcanum