How to update the filename of a Djangos FileField instance?

2024/5/20 12:26:08

Here a simple django model:

class SomeModel(models.Model):title = models.CharField(max_length=100)video = models.FileField(upload_to='video')

I would like to save any instance so that the video's file name would be a valid file name of the title.

For example, in the admin interface, I load a new instance with title "Lorem ipsum" and a video called "video.avi". The copy of the file on the server should be "Lorem Ipsum.avi" (or "Lorem_Ipsum.avi").

Thank you :)

Answer

If it just happens during save, as per the docs, you can pass a function to upload_to that will get called with the instance and the original filename and needs to return a string to be used as the filename. Maybe something like:

from django.template.defaultfilters import slugify
class SomeModel(models.Model):title = models.CharField(max_length=100)def video_filename(instance, filename):fname, dot, extension = filename.rpartition('.')slug = slugify(instance.title)return '%s.%s' % (slug, extension) video = models.FileField(upload_to=video_filename)
https://en.xdnf.cn/q/72649.html

Related Q&A

CSS Templating system for Django / Python?

Im wondering if there is anything like Djangos HTML templating system, for for CSS.. my searches on this arent turning up anything of use. I am aware of things like SASS and CleverCSS but, as far as I …

How to use chomedriver with a proxy for selenium webdriver?

Our network environment using a proxy server to connect to the outside internet, configured in IE => Internet Options => Connections => LAN Settings, like "10.212.20.11:8080".Now, Im…

django application static files not working in production

static files are not working in production even for the admin page.I have not added any static files.I am having issues with my admin page style.I have followed the below tutorial to create the django …

Celery task in Flask for uploading and resizing images and storing it to Amazon S3

Im trying to create a celery task for uploading and resizing an image before storing it to Amazon S3. But it doesnt work as expected. Without the task everything is working fine. This is the code so fa…

Python logger formatting is not formatting the string

Following are the contents of mylogger.py:def get_logger(name=my_super_logger):log = logging.getLogger(name)log.setLevel(logging.DEBUG)formatter = logging.Formatter(fmt=%(asctime)s %(name)s %(message)s…

Python subprocess.Popen.wait() returns 0 even though an error occured

I am running a command line utility via Pythons subprocess module. I create a subprocess.Popen() object with the command line arguments and stdout=subprocess.PIPE and then I use subprocess.wait() to w…

Better way to call a chain of functions in python?

I have a chain of operations which needs to occur one after the other and each depends on the previous functions output.Like this:out1 = function1(initial_input) out2 = function2(out1) out3 = function3…

Pytest text annotation for test with tuple of parameters

Im looking for more elegant solution for this kind of problem:def ids(x):if isinstance(x, int):return str(x)elif isinstance(x, str):return x[0]@pytest.mark.parametrize("number, string",[(1, &…

OpenCV wont capture from MacBook Pro iSight

Since a couple of days I cant open my iSight camera from inside an opencv application any more. cap = cv2.VideoCapture(0) returns, and cap.isOpened() returns true. However, cap.grab() just returns fals…

SQLAlchemy filter on list attribute

I have the following model defined with Flask-SQLAlchemy:"""models.py"""from flask_sqlalchemy import SQLAlchemydb = SQLAlchemy()skill_candidate = db.Table(SkillCandidate,d…