Программное назначение существующего анимированного GIF-изображения из статического каталога в поле ImageField экземпляра модели
OK. Допустим, у меня есть этот GIF, расположенный по адресу:
static/myproject/img/coming-soon.gif
Модель Django с именем "Note" с ImageField
.
class Note(models.Model):
featured_image = models.ImageField(upload_to=my_irrelevant_function, blank=True, max_length=155)
Я хочу сказать: Если featured_image
модели Note не существует, я хочу присвоить файл "coming-soon.gif" экземпляру.
Примечание: Я не могу установить default="some/path/to/my/coming-soon.gif
по причинам, в которые я не хочу вдаваться. Пожалуйста, считайте, что я не могу.
Вот coming-soon.gif:
Это 12 кадров:
>>> img.n_frames
12
Текущая ситуация с кодом:
from django.core.files.images import ImageFile
from django.core.files.base import File, ContentFile
from django.conf import settings
from django.views.generic import CreateView
from PIL import Image
from io import BytesIO
...
class NoteCreateView(CreateView):
def create_featured_image_if_none(self):
if (self.object.pk is not None) and (not self.object.featured_image):
img = Image.open(settings.COMING_SOON_IMAGE)
self.object.featured_image.save(f'{self.object.slug}.gif',
content=File(open(settings.COMING_SOON_IMAGE, 'rb')))
self.object.save()
Этот код создает неанимированный gif.
Я видел такие примеры:
gif[0].save('temp_result.gif', save_all=True, append_images=gif[1:], loop=0)
но мне не ясно:
- Do I even NEED to loop through each frame to compile a list of frames to pass to
append_images
when I already have the actual GIF image I want to assign to my model's instance? - How would I even loop through? I've seen seek(#) and tell() but wouldn't I just be recreating the entire GIF from scratch? I don't see how seek() and tell() give me the actual image frame or how to append it to some list.
Я могу использовать Python Pillow (PIL) или любой другой метод. Я надеюсь найти действительно чистое решение.