diff --git a/bots/modules/overlay.py b/bots/modules/overlay.py index 3d4b7ce..57abac7 100644 --- a/bots/modules/overlay.py +++ b/bots/modules/overlay.py @@ -4,6 +4,8 @@ from time import sleep from PIL import Image from django.db import models +from django import forms +from django.forms import modelformset_factory from telegram import Update from telegram.ext import Dispatcher, CallbackContext, MessageHandler, Filters, CommandHandler @@ -14,7 +16,6 @@ class OverlayBotModuleConfig(TelegramBotModuleConfig): start_text = models.TextField(null=True, blank=True) type_error_text = models.TextField(null=True, blank=True) comment = models.TextField(blank=True, null=True) - image = models.ImageField() MODULE_NAME = 'Overlay' @@ -32,7 +33,7 @@ class OverlayBotModuleConfig(TelegramBotModuleConfig): out = os.path.join(d, 'out.png') q = update.effective_message.photo[-1].get_file().download(src) im = Image.open(q).convert('RGBA') # type: Image.Image - overlay = Image.open(self.image.path).convert('RGBA') # type: Image.Image + overlay = Image.open(self.images.order_by('?').first().image.path).convert('RGBA') # type: Image.Image w, h = im.size min_side = min(w, h) overlay = overlay.resize((min_side, min_side), Image.LANCZOS) @@ -45,3 +46,30 @@ class OverlayBotModuleConfig(TelegramBotModuleConfig): dispatcher.add_handler(MessageHandler(Filters.photo, self.photo_handler)) dispatcher.add_handler(MessageHandler(Filters.all, self.message_handler)) return dispatcher + + @staticmethod + def form_context_data(view, instance=None): + ImageFormSet = modelformset_factory(OverlayImage, form=ImageForm, extra=3, can_delete=True) + formset = ImageFormSet(queryset=instance.images.all() if instance else OverlayImage.objects.none()) + return { + 'formset': formset, + } + + @staticmethod + def form_valid(view, bots_form, config_form): + ImageFormSet = modelformset_factory(OverlayImage, form=ImageForm, extra=3, can_delete=True) + formset = ImageFormSet(view.request.POST, view.request.FILES, queryset=config_form.instance.images.all()) + formset.save() + + +class OverlayImage(models.Model): + config = models.ForeignKey(OverlayBotModuleConfig, on_delete=models.CASCADE, related_name='images') + image = models.ImageField() + + +class ImageForm(forms.ModelForm): + image = forms.ImageField(widget=forms.ClearableFileInput(attrs={'accept': 'image/png'})) + + class Meta: + model = OverlayImage + fields = 'image', diff --git a/bots/templates/cabinet/bots/bot_form.html b/bots/templates/cabinet/bots/bot_form.html index 327d15f..47b6127 100644 --- a/bots/templates/cabinet/bots/bot_form.html +++ b/bots/templates/cabinet/bots/bot_form.html @@ -18,6 +18,12 @@