Exemplo n.º 1
0
class NewNewsForm(forms.Form):

    caption = fields.CharField(label='Заголовок')
    description = fields.TextField(label='Кратко')
    content = fields.TextField(label='Полностью')

    @classmethod
    def get_initials(cls, news):
        return {
            'caption': news.caption,
            'description': news.description,
            'content': news.content
        }
Exemplo n.º 2
0
    def __init__(self, key, verificators, *args, **kwargs):
        super(TemplateForm, self).__init__(*args, **kwargs)
        self.key = key
        self.verificators = copy.deepcopy(verificators)

        for i, verificator in enumerate(self.verificators):
            self.fields['verificator_%d' % i] = fields.TextField(
                label=verificator.get_label(),
                required=False,
                widget=django_forms.Textarea(attrs={'rows': 3}))

        for variable in self.key.variables:
            for restrictions_group in variable.type.restrictions:
                field_name = 'restriction_%s_%d' % (variable.value,
                                                    restrictions_group.value)

                restrictions = storage.restrictions_storage.get_restrictions(
                    restrictions_group)

                restrictions_choices = [(restriction.id, restriction.name)
                                        for restriction in restrictions]

                choices = [('', 'нет')]

                if restrictions_group.sort:
                    choices += sorted(restrictions_choices, key=lambda r: r[1])
                else:
                    choices += restrictions_choices

                self.fields[field_name] = fields.ChoiceField(
                    label=restrictions_group.text,
                    required=False,
                    choices=choices)
Exemplo n.º 3
0
class LoadDictionaryForm(forms.Form):
    words = fields.TextField(label='Данные словаря')

    def clean_words(self):
        data = self.cleaned_data.get('words')

        if data is None:
            raise ValidationError('Нет данных', code='not_json')

        try:
            words_data = s11n.from_json(data)
        except ValueError:
            raise ValidationError('Данные должны быть в формате JSON',
                                  code='not_json')

        try:
            words = [
                utg_words.Word.deserialize(word_data)
                for word_data in words_data.get('words')
            ]
        except:
            raise ValidationError('Неверный формат описания слов',
                                  code='wrong_words_format')

        return words
Exemplo n.º 4
0
class BaseUserForm(forms.Form):
    caption = fields.CharField(label='Название записи',
                               max_length=models.Bill.CAPTION_MAX_LENGTH,
                               min_length=models.Bill.CAPTION_MIN_LENGTH)

    chronicle_on_accepted = fields.TextField(
        label='Текст летописи при принятии (от {} до {} символов)'.format(
            conf.bills_settings.CHRONICLE_MIN_LENGTH,
            conf.bills_settings.CHRONICLE_MAX_LENGTH),
        widget=Textarea(attrs={'rows': 6}),
        min_length=conf.bills_settings.CHRONICLE_MIN_LENGTH,
        max_length=conf.bills_settings.CHRONICLE_MAX_LENGTH)

    depends_on = fields.ChoiceField(label='Зависит от', required=False)

    def __init__(self, *args, **kwargs):
        original_bill_id = kwargs.pop('original_bill_id', None)

        super().__init__(*args, **kwargs)

        voting_bills = models.Bill.objects.filter(
            state=relations.BILL_STATE.VOTING)
        self.fields['depends_on'].choices = [(None, ' — ')] + [
            (bill.id, bill.caption)
            for bill in voting_bills if bill.id != original_bill_id
        ]

    def clean_depends_on(self):
        data = self.cleaned_data.get('depends_on')

        if data == 'None':
            return None

        return data
Exemplo n.º 5
0
class BaseUserForm(forms.Form):
    RATIONALE_MIN_LENGTH = 250 if not project_settings.TESTS_RUNNING else 0

    caption = fields.CharField(label='Название записи', max_length=Bill.CAPTION_MAX_LENGTH, min_length=Bill.CAPTION_MIN_LENGTH)
    rationale = bbcode.BBField(label='', min_length=RATIONALE_MIN_LENGTH)

    chronicle_on_accepted = fields.TextField(label='Текст летописи при принятии', widget=Textarea(attrs={'rows': 2}),
                                             min_length=bills_settings.CHRONICLE_MIN_LENGTH, max_length=bills_settings.CHRONICLE_MAX_LENGTH)
Exemplo n.º 6
0
class BanForm(forms.Form):
    ban_type = fields.TypedChoiceField(label='тип',
                                       choices=relations.BAN_TYPE.choices(),
                                       coerce=relations.BAN_TYPE.get_from_name)
    ban_time = fields.TypedChoiceField(label='длительность',
                                       choices=relations.BAN_TIME.choices(),
                                       coerce=relations.BAN_TIME.get_from_name)

    description = fields.TextField(label='обоснование', required=True)
Exemplo n.º 7
0
class RecipientsForm(forms.Form):

    recipients = fields.TextField(label='', widget=HiddenInput())

    def clean_recipients(self):
        recipients = self.cleaned_data['recipients']

        try:
            recipients = [int(id_.strip()) for id_ in recipients.split(',')]
        except ValueError:
            raise ValidationError(u'Неверный идентификатор получателя')

        return recipients
Exemplo n.º 8
0
class GMForm(forms.Form):
    amount = fields.IntegerField(label='Печеньки')
    description = fields.TextField(label='Описание', required=True)
Exemplo n.º 9
0
class TemplateForm(forms.Form):
    template = fields.TextField(
        label='Шаблон',
        min_length=1,
        widget=django_forms.Textarea(attrs={'rows': 3}))

    def __init__(self, key, verificators, *args, **kwargs):
        super(TemplateForm, self).__init__(*args, **kwargs)
        self.key = key
        self.verificators = copy.deepcopy(verificators)

        for i, verificator in enumerate(self.verificators):
            self.fields['verificator_%d' % i] = fields.TextField(
                label=verificator.get_label(),
                required=False,
                widget=django_forms.Textarea(attrs={'rows': 3}))

        for variable in self.key.variables:
            for restrictions_group in variable.type.restrictions:
                field_name = 'restriction_%s_%d' % (variable.value,
                                                    restrictions_group.value)

                restrictions = storage.restrictions_storage.get_restrictions(
                    restrictions_group)

                restrictions_choices = [(restriction.id, restriction.name)
                                        for restriction in restrictions]

                choices = [('', 'нет')]

                if restrictions_group.sort:
                    choices += sorted(restrictions_choices, key=lambda r: r[1])
                else:
                    choices += restrictions_choices

                self.fields[field_name] = fields.ChoiceField(
                    label=restrictions_group.text,
                    required=False,
                    choices=choices)

    def verificators_fields(self):
        return [
            self['verificator_%d' % i]
            for i, verificator in enumerate(self.verificators)
        ]

    def variable_restrictions_fields(self, variable):
        x = [
            self['restriction_%s_%d' %
                 (variable.value, restrictions_group.value)]
            for restrictions_group in variable.type.restrictions
        ]
        return x

    def clean(self):
        cleaned_data = super(TemplateForm, self).clean()

        for i, verificator in enumerate(self.verificators):
            verificator.text = cleaned_data['verificator_%d' % i]

        return cleaned_data

    def get_restrictions(self):
        restrictions = []

        for variable in self.key.variables:
            for restrictions_group in variable.type.restrictions:
                field_name = 'restriction_%s_%d' % (variable.value,
                                                    restrictions_group.value)

                restriction_id = self.cleaned_data.get(field_name)

                if not restriction_id:
                    continue

                restrictions.append((variable.value, int(restriction_id)))

        return frozenset(restrictions)

    def clean_template(self):
        data = self.cleaned_data['template'].strip()

        # TODO: test exceptions
        try:
            template = utg_templates.Template()
            template.parse(data,
                           externals=[v.value for v in self.key.variables])
        except utg_exceptions.WrongDependencyFormatError as e:
            raise django_forms.ValidationError(
                'Ошибка в формате подстановки: %s' % e.arguments['dependency'])
        except utg_exceptions.UnknownVerboseIdError as e:
            raise django_forms.ValidationError('Неизвестная форма слова: %s' %
                                               e.arguments['verbose_id'])
        except utg_exceptions.ExternalDependecyNotFoundError as e:
            raise django_forms.ValidationError('Неизвестная переменная: %s' %
                                               e.arguments['dependency'])

        return data

    @classmethod
    def get_initials(cls, template, verificators):
        initials = {'template': template.raw_template}

        for i, verificator in enumerate(verificators):
            initials['verificator_%d' % i] = verificator.text

        for variable, restrictions in template.restrictions.items():
            for restriction in restrictions:
                field_name = 'restriction_%s_%d' % (variable.value,
                                                    restriction.group.value)
                initials[field_name] = restriction.id

        return initials
Exemplo n.º 10
0
class GiveAwardForm(forms.Form):
    type = fields.TypedChoiceField(label='тип', choices=relations.AWARD_TYPE.choices(), coerce=relations.AWARD_TYPE.get_from_name)
    description = fields.TextField(label='обоснование', required=False)
Exemplo n.º 11
0
class TemplateForm(forms.Form):
    template = fields.TextField(
        label='Шаблон',
        min_length=1,
        widget=django_forms.Textarea(attrs={'rows': 3}))

    def __init__(self, key, verificators, *args, **kwargs):
        super(TemplateForm, self).__init__(*args, **kwargs)
        self.key = key
        self.verificators = copy.deepcopy(verificators)

        for i, verificator in enumerate(self.verificators):
            self.fields['verificator_%d' % i] = fields.TextField(
                label=verificator.get_label(),
                required=False,
                widget=django_forms.Textarea(attrs={'rows': 3}))

        for variable in self.key.variables:
            for restrictions_group in variable.type.restrictions:
                field_name = 'restriction_%s_%d' % (variable.value,
                                                    restrictions_group.value)

                restrictions = storage.restrictions_storage.get_restrictions(
                    restrictions_group)

                restrictions_choices = [(restriction.id, restriction.name)
                                        for restriction in restrictions]

                choices = [('', 'нет')]

                if restrictions_group.sort:
                    choices += sorted(restrictions_choices, key=lambda r: r[1])
                else:
                    choices += restrictions_choices

                self.fields[field_name] = fields.ChoiceField(
                    label=restrictions_group.text,
                    required=False,
                    choices=choices)

    def verificators_fields(self):
        return [
            self['verificator_%d' % i]
            for i, verificator in enumerate(self.verificators)
        ]

    def variable_restrictions_fields(self, variable):
        x = [
            self['restriction_%s_%d' %
                 (variable.value, restrictions_group.value)]
            for restrictions_group in variable.type.restrictions
        ]
        return x

    def clean(self):
        cleaned_data = super(TemplateForm, self).clean()

        for i, verificator in enumerate(self.verificators):
            verificator.text = cleaned_data['verificator_%d' % i]

        if self.key.group.is_HERO_HISTORY:
            self.check_hero_history_restrictions()

        return cleaned_data

    def check_hero_history_restrictions(self):
        current_restrictions = self.get_restrictions()

        allowed_reistrictions = {
            lexicon_relations.VARIABLE.HERO.value: {
                relations.TEMPLATE_RESTRICTION_GROUP.GENDER:
                [record.value for record in game_relations.GENDER.records],
                relations.TEMPLATE_RESTRICTION_GROUP.RACE:
                [record.value for record in game_relations.RACE.records],
                relations.TEMPLATE_RESTRICTION_GROUP.HABIT_HONOR: [
                    game_relations.HABIT_HONOR_INTERVAL.LEFT_1.value,
                    game_relations.HABIT_HONOR_INTERVAL.RIGHT_1.value
                ],
                relations.TEMPLATE_RESTRICTION_GROUP.HABIT_PEACEFULNESS: [
                    game_relations.HABIT_PEACEFULNESS_INTERVAL.LEFT_1.value,
                    game_relations.HABIT_PEACEFULNESS_INTERVAL.RIGHT_1.value
                ],
                relations.TEMPLATE_RESTRICTION_GROUP.ARCHETYPE:
                [record.value for record in game_relations.ARCHETYPE.records],
                relations.TEMPLATE_RESTRICTION_GROUP.UPBRINGING: [
                    record.value
                    for record in beings_relations.UPBRINGING.records
                ],
                relations.TEMPLATE_RESTRICTION_GROUP.FIRST_DEATH: [
                    record.value
                    for record in beings_relations.FIRST_DEATH.records
                ],
                relations.TEMPLATE_RESTRICTION_GROUP.AGE:
                [record.value for record in beings_relations.AGE.records]
            }
        }

        for variable_value, restriction_id in current_restrictions:
            if variable_value not in allowed_reistrictions:
                raise django_forms.ValidationError(
                    'Ограничения для переменной «{}» нельзя использовать в этой фразе'
                    .format(variable_value))

            restriction = storage.restrictions_storage[restriction_id]

            if restriction.group not in allowed_reistrictions[variable_value]:
                field_name = 'restriction_%s_%d' % (variable_value,
                                                    restriction.group.value)
                message_template = 'Тип ограничений «{}» для переменной «{}» нельзя использовать в этой фразе'
                raise django_forms.ValidationError({
                    field_name:
                    message_template.format(restriction.group.text,
                                            variable_value)
                })

            if restriction.external_id not in allowed_reistrictions[
                    variable_value][restriction.group]:
                field_name = 'restriction_%s_%d' % (variable_value,
                                                    restriction.group.value)
                message_template = 'Текущие занчения типа  ограничений «{}» для переменной «{}» нельзя использовать в этой фразе'
                raise django_forms.ValidationError({
                    field_name:
                    message_template.format(restriction.group.text,
                                            variable_value)
                })

        for template_model in models.Template.objects.filter(
                key=self.key).iterator():
            template = prototypes.TemplatePrototype(template_model)
            if template.raw_restrictions == frozenset(current_restrictions):
                message_template = 'Фраза с такими ограничениями уже есть, её идентификатор: {}. Не может быть двух фраз истории с одинаковыми ограничениями.'
                raise django_forms.ValidationError(
                    message_template.format(template.id))

    def get_restrictions(self):
        restrictions = []

        for variable in self.key.variables:
            for restrictions_group in variable.type.restrictions:
                field_name = 'restriction_%s_%d' % (variable.value,
                                                    restrictions_group.value)

                restriction_id = self.cleaned_data.get(field_name)

                if not restriction_id:
                    continue

                restrictions.append((variable.value, int(restriction_id)))

        return frozenset(restrictions)

    def clean_template(self):
        data = self.cleaned_data['template'].strip()

        # TODO: test exceptions
        try:
            template = utg_templates.Template()
            template.parse(data,
                           externals=[v.value for v in self.key.variables])
        except utg_exceptions.WrongDependencyFormatError as e:
            raise django_forms.ValidationError(
                'Ошибка в формате подстановки: %s' % e.arguments['dependency'])
        except utg_exceptions.UnknownVerboseIdError as e:
            raise django_forms.ValidationError('Неизвестная форма слова: %s' %
                                               e.arguments['verbose_id'])
        except utg_exceptions.ExternalDependecyNotFoundError as e:
            raise django_forms.ValidationError('Неизвестная переменная: %s' %
                                               e.arguments['dependency'])

        return data

    @classmethod
    def get_initials(cls, template, verificators):
        initials = {'template': template.raw_template}

        for i, verificator in enumerate(verificators):
            initials['verificator_%d' % i] = verificator.text

        for variable, restrictions in template.restrictions.items():
            for restriction in restrictions:
                field_name = 'restriction_%s_%d' % (variable.value,
                                                    restriction.group.value)
                initials[field_name] = restriction.id

        return initials