<commit_before>import datetime

from django import forms
from django.db import models
from django.contrib.admin import TabularInline
from django.contrib.admin.widgets import AdminFileWidget
from django.forms.widgets import (TextInput,
                                  NumberInput,
                                  Textarea,
                                  SelectMultiple,
                                  ClearableFileInput,
                                  )
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _

from .models import ResidentalComplexImage, ResidentalComplex, NewBuilding


# it is new sizes for widgets in Inlines
standart_formfield_overrides = {
    models.CharField: {'widget': TextInput(attrs={'size': '10'})},
    models.PositiveSmallIntegerField: {'widget': NumberInput(attrs={'size': '3'})},
    models.IntegerField: {'widget': NumberInput(attrs={'style': 'width:6ch', })},
    models.DecimalField: {'widget': NumberInput(attrs={'style': 'width:12ch', })},
    models.TextField: {'widget': Textarea(attrs={'cols': 2, 'rows': 2})},
}


class AdminImageWidget(AdminFileWidget):
    ''' it base widget which allows to show loaded image near to the 'browse' button '''

    def render(self, name, value, attrs=None):
        output = []
        if value and getattr(value, "url", None):
            image_url = value.url
            file_name = str(value)
            output.append(u'<br><a href="%s" target="_blank"><img src="%s" alt="%s"  width=150/></a><br>' %
                          (image_url, image_url, file_name))
        output.append(super(AdminFileWidget, self).render(name, value, attrs))
        return mark_safe(u''.join(output))


class TabularInlineWithImageWidgetInline(TabularInline):
    ''' it is inline which allows to show loaded image near to the 'browse' button into it'''
    # image_fields - fields which images will be shown in admin
    image_fields = []

    def formfield_for_dbfield(self, db_field, **kwargs):
        if db_field.name in self.image_fields:
            request = kwargs.pop("request", None)
            kwargs['widget'] = AdminImageWidget
            return db_field.formfield(**kwargs)
        return super(TabularInlineWithImageWidgetInline, self).formfield_for_dbfield(db_field, **kwargs)


class PhotoAdminForm(forms.ModelForm):

    class Meta:
        model = ResidentalComplexImage
        widgets = {'image': ClearableFileInput(attrs={'multiple': True})}
        fields = '__all__'

    def save(self, *args, **kwargs):
        image_name_initial = 'image'
        image_name = image_name_initial
        rc_name_initial = 'residental_complex'
        rc_name = rc_name_initial
        id_initial = 'id'
        id_ = id_initial
        if self.prefix:
            image_name = "%s-%s" % (self.prefix, image_name)
            rc_name = "%s-%s" % (self.prefix, rc_name)
            id_ = "%s-%s" % (self.prefix, id_)

        self.files.__dict__[image_name_initial] = self.data[image_name]
        files_list = self.files.getlist(image_name_initial)
        print(self.files.getlist(image_name))
        # print(self)
        print('\n--------')
        print(self.data[rc_name])
        answer = super().save(*args, **kwargs)
        self.data[rc_name_initial] = self.data[rc_name]
        self.data[id_initial] = self.data[id_]
        #self.files.__dict__[image_name_initial]= self.data[image_name]
        print('\n--------')
        print('"%s"' % self.data[rc_name_initial])
        print('\n--------3')
        # print(self.image)
        print('\n--------')
        if len(files_list) > 1:
            files_list.pop()

            img = self.cleaned_data.get(image_name)
            # fields, self.files)
            new_form = PhotoAdminForm(self.data, self.files)
            new_form.image = self.files.get(image_name)
            if new_form.is_valid():
                new_form.save()
            else:
                for field in new_form:
                    print(field)
                    for error in field.errors:
                        print(error)
                print(new_form.non_field_errors())
                raise Exception()
        return answer


params_for_decimal_from = {"min_value": 0,
                           "decimal_places": 1, 'required': False}
params_for_decimal_to = params_for_decimal_from.copy()

params_for_decimal_from['widget'] = forms.NumberInput(
    attrs={'placeholder': _('от')})
params_for_decimal_to['widget'] = forms.NumberInput(
    attrs={'placeholder': _('до')})


def SETTLEMENT_CHOICES():
    yield ('', _('Не важно'))
    yield (True, _('Уже'))

    def last_day_of_month(any_day):
        next_month = any_day.replace(
            day=28) + datetime.timedelta(days=4)  # this will never fail
        return next_month - datetime.timedelta(days=next_month.day)

    QUARTER_1 = 1
    QUARTER_2 = 2
    QUARTER_3 = 3
    QUARTER_4 = 4
    QUARTERS = (QUARTER_1, QUARTER_2, QUARTER_3, QUARTER_4)

    for optgroup in (2018, 2019, 2020):
        optgroup_choices = []
        for QUARTER in QUARTERS:
            optgroup_choices.append(
                (
                    last_day_of_month(datetime.date(optgroup, QUARTER*3, 1)),
                    (_("%(number_of_quarter)s квартал %(year)s") % {'number_of_quarter': QUARTER,
                                                                    'year': optgroup})
                )
            )
        yield (optgroup, optgroup_choices)


class SearchForm(forms.Form):
    ROOMS_CHOICES = (<commit_msg>Set up date filter (settlement before).<commit_after>import datetime

from django import forms
from django.db import models
from django.contrib.admin import TabularInline
from django.contrib.admin.widgets import AdminFileWidget
from django.forms.widgets import (TextInput,
                                  NumberInput,
                                  Textarea,
                                  SelectMultiple,
                                  ClearableFileInput,
                                  )
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _

from .models import ResidentalComplexImage, ResidentalComplex, NewBuilding


# it is new sizes for widgets in Inlines
standart_formfield_overrides = {
    models.CharField: {'widget': TextInput(attrs={'size': '10'})},
    models.PositiveSmallIntegerField: {'widget': NumberInput(attrs={'size': '3'})},
    models.IntegerField: {'widget': NumberInput(attrs={'style': 'width:6ch', })},
    models.DecimalField: {'widget': NumberInput(attrs={'style': 'width:12ch', })},
    models.TextField: {'widget': Textarea(attrs={'cols': 2, 'rows': 2})},
}


class AdminImageWidget(AdminFileWidget):
    ''' it base widget which allows to show loaded image near to the 'browse' button '''

    def render(self, name, value, attrs=None):
        output = []
        if value and getattr(value, "url", None):
            image_url = value.url
            file_name = str(value)
            output.append(u'<br><a href="%s" target="_blank"><img src="%s" alt="%s"  width=150/></a><br>' %
                          (image_url, image_url, file_name))
        output.append(super(AdminFileWidget, self).render(name, value, attrs))
        return mark_safe(u''.join(output))


class TabularInlineWithImageWidgetInline(TabularInline):
    ''' it is inline which allows to show loaded image near to the 'browse' button into it'''
    # image_fields - fields which images will be shown in admin
    image_fields = []

    def formfield_for_dbfield(self, db_field, **kwargs):
        if db_field.name in self.image_fields:
            request = kwargs.pop("request", None)
            kwargs['widget'] = AdminImageWidget
            return db_field.formfield(**kwargs)
        return super(TabularInlineWithImageWidgetInline, self).formfield_for_dbfield(db_field, **kwargs)


class PhotoAdminForm(forms.ModelForm):

    class Meta:
        model = ResidentalComplexImage
        widgets = {'image': ClearableFileInput(attrs={'multiple': True})}
        fields = '__all__'

    def save(self, *args, **kwargs):
        image_name_initial = 'image'
        image_name = image_name_initial
        rc_name_initial = 'residental_complex'
        rc_name = rc_name_initial
        id_initial = 'id'
        id_ = id_initial
        if self.prefix:
            image_name = "%s-%s" % (self.prefix, image_name)
            rc_name = "%s-%s" % (self.prefix, rc_name)
            id_ = "%s-%s" % (self.prefix, id_)

        self.files.__dict__[image_name_initial] = self.data[image_name]
        files_list = self.files.getlist(image_name_initial)
        print(self.files.getlist(image_name))
        # print(self)
        print('\n--------')
        print(self.data[rc_name])
        answer = super().save(*args, **kwargs)
        self.data[rc_name_initial] = self.data[rc_name]
        self.data[id_initial] = self.data[id_]
        #self.files.__dict__[image_name_initial]= self.data[image_name]
        print('\n--------')
        print('"%s"' % self.data[rc_name_initial])
        print('\n--------3')
        # print(self.image)
        print('\n--------')
        if len(files_list) > 1:
            files_list.pop()

            img = self.cleaned_data.get(image_name)
            # fields, self.files)
            new_form = PhotoAdminForm(self.data, self.files)
            new_form.image = self.files.get(image_name)
            if new_form.is_valid():
                new_form.save()
            else:
                for field in new_form:
                    print(field)
                    for error in field.errors:
                        print(error)
                print(new_form.non_field_errors())
                raise Exception()
        return answer


params_for_decimal_from = {"min_value": 0,
                           "decimal_places": 1, 'required': False}
params_for_decimal_to = params_for_decimal_from.copy()

params_for_decimal_from['widget'] = forms.NumberInput(
    attrs={'placeholder': _('от')})
params_for_decimal_to['widget'] = forms.NumberInput(
    attrs={'placeholder': _('до')})


def SETTLEMENT_CHOICES():
    yield ('', _('Не важно'))
    yield (datetime.date.today(), _('Уже'))

    def last_day_of_month(any_day):
        next_month = any_day.replace(
            day=28) + datetime.timedelta(days=4)  # this will never fail
        return next_month - datetime.timedelta(days=next_month.day)

    QUARTER_1 = 1
    QUARTER_2 = 2
    QUARTER_3 = 3
    QUARTER_4 = 4
    QUARTERS = (QUARTER_1, QUARTER_2, QUARTER_3, QUARTER_4)

    for optgroup in (2018, 2019, 2020):
        optgroup_choices = []
        for QUARTER in QUARTERS:
            optgroup_choices.append(
                (
                    last_day_of_month(datetime.date(optgroup, QUARTER*3, 1)),
                    (_("%(number_of_quarter)s квартал %(year)s") % {'number_of_quarter': QUARTER,
                                                                    'year': optgroup})
                )
            )
        yield (optgroup, optgroup_choices)


class SearchForm(forms.Form):
    ROOMS_CHOICES = (
{'fraction_non_alphanumeric': 0.12229699416778825, 'fraction_numerical': 0.007895917451772094, 'mean_word_length': 2.3064372589735984, 'pattern_counts': {'":': 4, '<': 13, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 12, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6259148', 'n_tokens_mistral': 3421, 'n_tokens_neox': 3309, 'n_words': 689}