Django: How to replace/overwrite/update/change a file of FileField?

前端 未结 2 1209
臣服心动
臣服心动 2020-12-16 00:53

In Django, I have the following model:

from django.db import models
from django.core.files.base import File
import os, os.path

class Project(models.Model):
         


        
2条回答
  •  借酒劲吻你
    2020-12-16 01:41

    I came across this problem recently myself, and solved it something like this:

    from django.db import models
    from django.core.files.base import File
    import os, os.path
    
    class Project(models.Model):
        video = models.FileField(upload_to="media")
    
        def replace_video(self):
            """Convert video to WebM format."""
            # This is where the conversion takes place,
            # returning a path to the new converted video
            # that I wish to override the old one.
            video_path = convert_video()
    
            # Replace old video with new one,
            # and remove original unconverted video and original copy of new video.
            old_path = self.video.path
            self.video.save(os.path.basename(video_path), File(open(video_path ,"wb")), save=True)
            os.remove(video_path)
            os.remove(old_path)
    

提交回复
热议问题