multi image upload

This commit is contained in:
bakatrouble 2020-02-10 18:57:55 +03:00
parent 319b550fc0
commit a5c4dfa7f5
5 changed files with 58 additions and 11 deletions

View File

@ -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',

View File

@ -18,6 +18,12 @@
<hr>
<h4>Module options</h4>
{% bootstrap_form config_form layout='horizontal' %}
{% if formset %}
{% bootstrap_form formset.management_form layout='horizontal' %}
{% for form in formset %}
{% bootstrap_form form layout='horizontal' %}
{% endfor %}
{% endif %}
</div>
<footer class="card-footer text-right">
{% if feed %}<a href="#delete-modal" class="modal-basic btn btn-danger">Delete</a>{% endif %}

View File

@ -29,7 +29,9 @@ class BaseBotConfigView(CabinetViewMixin, TemplateView):
if bot_form.is_valid() and config_form.is_valid():
return self.form_valid(bot_form, config_form)
else:
context = self.get_context_data(forms=(bot_form, config_form))
context = self.get_context_data(
forms=(bot_form, config_form)
)
return self.render_to_response(context)
def get_forms(self):
@ -43,9 +45,16 @@ class BaseBotConfigView(CabinetViewMixin, TemplateView):
def get_context_data(self, forms=None, **kwargs):
ctx = super(BaseBotConfigView, self).get_context_data(**kwargs)
ctx['bot_form'], ctx['config_form'] = self.get_forms() if forms is None else forms
ctx['bot_module'] = self.get_content_type().model_class()
ctx['bot_module'] = model = self.model
if hasattr(model, 'form_context_data'):
bot = self.get_object()
ctx.update(model.form_context_data(self, bot.config if bot else None))
return ctx
@property
def model(self):
return self.get_content_type().model_class()
# django-braces
class AjaxResponseMixin(object):

View File

@ -40,6 +40,8 @@ class BotConfigEditView(BaseBotConfigView, SingleObjectMixin):
def form_valid(self, bot_form, config_form):
bot_form.save()
config_form.save()
if hasattr(self.model, 'form_valid'):
self.model.form_valid(self, bot_form, config_form)
cache.set('bots_reset', '1')
messages.success(self.request, 'Config was successfully saved')
return HttpResponseRedirect('')
@ -55,15 +57,17 @@ class BotConfigCreateView(BaseBotConfigView):
def get_object(self):
return None
def form_valid(self, bots_form, config_form):
def form_valid(self, bot_form, config_form):
config_form.save()
bots_form.instance.owner = self.request.user
bots_form.instance.config_type = self.get_content_type()
bots_form.instance.config_id = config_form.instance.pk
bots_form.save()
bot_form.instance.owner = self.request.user
bot_form.instance.config_type = self.get_content_type()
bot_form.instance.config_id = config_form.instance.pk
bot_form.save()
if hasattr(self.model, 'form_valid'):
self.model.form_valid(self, bot_form, config_form)
cache.set('bots_reset', '1')
messages.success(self.request, 'Config was successfully saved')
return redirect('cabinet:bots:edit', pk=bots_form.instance.pk)
return redirect('cabinet:bots:edit', pk=bot_form.instance.pk)
def get_content_type(self):
return get_object_or_404(ContentType, model=self.kwargs['content_type'])

View File

@ -58,7 +58,7 @@ class TurbolinksMiddleware:
def get_config_form(mdl):
class ConfigForm(ModelForm):
class ConfigForm(mdl.CONFIG_FORM_CLASS if hasattr(mdl, 'CONFIG_FORM_CLASS') else ModelForm):
prefix = 'config'
class Meta: