Trong Django, tôi có mô hình sau đây:Django: Làm cách nào để thay thế/ghi đè/cập nhật/thay đổi tệp của FileField?
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.
self.video.delete(save=True)
self.video.save(os.path.basename(video_path), File(open(video_path ,"wb")), save=True)
os.remove(video_path)
Tôi muốn để có thể thay thế file trong FileField Video trên một mô hình đối tượng/ví dụ. Phương pháp trên tôi đã viết không hoạt động. Khi tôi xóa tệp gốc, tôi nhận được thông báo lỗi sau:
ValueError: The 'video' attribute has no file associated with it.
Làm cách nào để thay thế tệp bằng tệp đã cập nhật và xóa tệp gốc (không cần thiết)?
Side-Note: Tôi đã tìm thấy một related issue, nhưng không có câu trả lời thỏa mãn.
Lựa chọn 1 thực sự có vẻ là một ý tưởng tốt. Cảm ơn! –