How do I create uuid4 filenames for images loaded with Django-CKEeditor?
I want to generate random uid filenames for images uploaded with django-ckeditor / uploader.
I created utils.py
in the same folder as settings.py
:
import uuid
def get_name_uid():
ext = filename.split('.')[-1]
filename = "%s.%s" % (uuid.uuid4(), ext)
return filename
I would like to add this "random" filename to settings.py
:
CKEDITOR_FILENAME_GENERATOR = get_name_uid()
How can i do this? I'm not sure how to get the name of the file being loaded into the editor. Should I pass the filename from settings.py to utils.py? Or is there another way to do this?
Their documentation says below :
``CKEDITOR_UPLOAD_PATH = "uploads/"``
When using default file system storage, images will be uploaded to "uploads" folder in your MEDIA_ROOT and urls will be created against MEDIA_URL (/media/uploads/image.jpg).
If you want be able for have control for filename generation, you have to add into settings yours custom filename generator.
```
# utils.py
def get_filename(filename):
return filename.upper()
```
```
# settings.py
CKEDITOR_FILENAME_GENERATOR = 'utils.get_filename'
```
CKEditor has been tested with django FileSystemStorage and S3BotoStorage.
There are issues using S3Storage from django-storages.
source to share
Basically, this is all written out for you in the documents:
def get_filename(filename):
return filename.upper() # returns the uppercase version of filename
So, the example function get_filename
gets the file name passed in and you should return the file name you want. This is what we call callback .
That the callback is passed as arguments is called the "callback signature" and the docs clearly define what it gets.
So, put the function where it makes sense . I would choose mysite/mysite/utils.py
, given the structure outlined in the tutorial, under the heading "Let's see what the generated project is:". So, in the same directory as settings.py
. I would call it generate_uuid4_filename
and it mysite/mysite/utils.py
will look like this:
import uuid
import os.path
def generate_uuid4_filename(filename):
"""
Generates a uuid4 (random) filename, keeping file extension
:param filename: Filename passed in. In the general case, this will
be provided by django-ckeditor uploader.
:return: Randomized filename in urn format.
:rtype: str
"""
discard, ext = os.path.splitext(filename)
basename = uuid.uuid4().urn
return ''.join(basename, ext)
Now update your settings.py
:
# Near the rest of the CKEditor variables
CKEDITOR_FILENAME_GENERATOR = '<app_label>.utils.generate_uuid4_filename'
And you're done. Good luck!
source to share