class UserForm(BaseUserForm): place = fields.ChoiceField(label=u'Город') new_modifier = fields.ChoiceField(label=u'Новая специализация') def __init__(self, *args, **kwargs): super(UserForm, self).__init__(*args, **kwargs) self.fields['place'].choices = places_storage.get_choices() self.fields['new_modifier'].choices = sorted(CITY_MODIFIERS.choices(), key=lambda m: m[1]) def clean_new_modifier(self): data = self.cleaned_data['new_modifier'] return CITY_MODIFIERS.get_from_name(data) def clean(self): cleaned_data = super(UserForm, self).clean() place = places_storage.get(int(cleaned_data['place'])) modifier = MODIFIERS[cleaned_data['new_modifier']](place) if not modifier.can_be_choosen: raise ValidationError( u'В данный момент город "%s" нельзя преобразовать в "%s".' % (place.name, modifier.NAME)) return cleaned_data
class NewAchievementForm(forms.Form): approved = fields.BooleanField(label=u'Одобрена', required=False) order = fields.IntegerField() group = fields.TypedChoiceField(label=u'Группа', choices=sorted(ACHIEVEMENT_GROUP.choices(), key=lambda g: g[1]), coerce=ACHIEVEMENT_GROUP.get_from_name) type = fields.TypedChoiceField(label=u'Тип', choices=sorted(ACHIEVEMENT_TYPE.choices(), key=lambda g: g[1]), coerce=ACHIEVEMENT_TYPE.get_from_name) caption = fields.CharField(label=u'Название', max_length=AchievementPrototype.CAPTION_MAX_LENGTH, min_length=1) description = bbcode.BBField(label=u'Описание', min_length=1, max_length=AchievementPrototype.DESCRIPTION_MAX_LENGTH) barrier = fields.IntegerField(label=u'Барьер') points = fields.IntegerField(label=u'Очки') item_1 = fields.ChoiceField(label=u'награда 1', choices=[], required=False) item_2 = fields.ChoiceField(label=u'награда 2', choices=[], required=False) item_3 = fields.ChoiceField(label=u'награда 3', choices=[], required=False) def __init__(self, *args, **kwargs): super(NewAchievementForm, self).__init__(*args, **kwargs) self.fields['item_1'].choices = [('', u'-----')] + items_storage.form_choices() self.fields['item_2'].choices = [('', u'-----')] + items_storage.form_choices() self.fields['item_3'].choices = [('', u'-----')] + items_storage.form_choices() clean_item_1 = create_clean_item_method(1) clean_item_2 = create_clean_item_method(2) clean_item_3 = create_clean_item_method(3)
class BaseForm(BaseUserForm): person_1 = fields.ChoiceField(label='Первый Мастер') person_2 = fields.ChoiceField(label='Второй Мастер') def __init__(self, person_1_id, person_2_id, *args, **kwargs): super(BaseForm, self).__init__(*args, **kwargs) self.fields['person_1'].choices = persons_objects.Person.form_choices(choosen_person=persons_storage.persons.get(person_1_id), predicate=self.person_filter) self.fields['person_2'].choices = persons_objects.Person.form_choices(choosen_person=persons_storage.persons.get(person_2_id), predicate=self.person_filter) def person_filter(self, place, person): return persons_storage.social_connections.has_connections(person) def clean(self): cleaned_data = super(BaseForm, self).clean() if 'person_1' not in cleaned_data or 'person_2' not in cleaned_data: return cleaned_data # error in one of that filed, no need to continue cleaning person_1 = persons_storage.persons[int(cleaned_data['person_1'])] person_2 = persons_storage.persons[int(cleaned_data['person_2'])] if person_1.id == person_2.id: raise ValidationError('Необхоимо выбрать двух разных Мастеров') connection = persons_storage.social_connections.get_connection(person_1, person_2) if connection is None: raise ValidationError('Мастера не имеют связи') if not connection.can_be_removed(): raise ValidationError('Эту связь пока нельзя разорвать, дождитесь пока она просуществует минимально допустимое время') return cleaned_data
class UserForm(BaseUserForm): place = fields.ChoiceField(label=u'Город') new_modifier = fields.TypedChoiceField(label=u'Новая специализация', choices=sorted( CITY_MODIFIERS.choices(), key=lambda g: g[1]), coerce=CITY_MODIFIERS.get_from_name) def __init__(self, *args, **kwargs): super(UserForm, self).__init__(*args, **kwargs) self.fields['place'].choices = places_storage.places.get_choices() def clean(self): cleaned_data = super(UserForm, self).clean() place = places_storage.places.get(int(cleaned_data['place'])) modifier = cleaned_data.get('new_modifier') if modifier: if not can_be_choosen(place, modifier): raise ValidationError( u'В данный момент город «%s» нельзя преобразовать в «%s».' % (place.name, modifier.text)) return cleaned_data
class EditKitForm(forms.Form): collection = fields.ChoiceField(label='Коллекция') caption = fields.CharField(label='Название', max_length=KitPrototype.CAPTION_MAX_LENGTH, min_length=1) description = bbcode.BBField( label='Описание', min_length=1, max_length=KitPrototype.DESCRIPTION_MAX_LENGTH) def __init__(self, *args, **kwargs): super(EditKitForm, self).__init__(*args, **kwargs) self.fields[ 'collection'].choices = collections_storage.get_form_choices() def clean_collection(self): collection_id = self.cleaned_data['collection'] collection = collections_storage[int(collection_id)] if collection is None: raise django_forms.ValidationError('Коллекция не найдена') return collection
class UserForm(BaseUserForm): person = fields.ChoiceField(label=u'Член Совета') def __init__(self, choosen_person_id, *args, **kwargs): super(UserForm, self).__init__(*args, **kwargs) self.fields['person'].choices = PersonPrototype.form_choices(only_weak=True, choosen_person=persons_storage.get(choosen_person_id))
class BaseForm(BaseUserForm): place = fields.ChoiceField(label='Город') new_race = fields.TypedChoiceField( label='Новая раса', choices=sorted([(record, record.multiple_text) for record in game_relations.RACE.records], key=lambda g: g[1]), coerce=game_relations.RACE.get_from_name) def __init__(self, *args, **kwargs): super(BaseForm, self).__init__(*args, **kwargs) self.fields['place'].choices = places_storage.places.get_choices() def clean(self): cleaned_data = super(BaseForm, self).clean() place = places_storage.places.get(int(cleaned_data['place'])) race = cleaned_data.get('new_race') if race: if race == place.race: raise ValidationError('Город уже принадлежит выбранной расе.') if not any(race == person.race for person in place.persons): raise ValidationError( 'В городе должен быть Мастер соответствующей расы.') return cleaned_data
class BaseForm(BaseUserForm): person = fields.ChoiceField(label='Житель') name = WordField(word_type=utg_relations.WORD_TYPE.NOUN, label='Название', skip_markers=(utg_relations.NOUN_FORM.COUNTABLE, )) x = forms.IntegerField(label='координата x') y = forms.IntegerField(label='координата y') def __init__(self, choosen_person_id, *args, **kwargs): # pylint: disable=W0613 super(BaseForm, self).__init__(*args, **kwargs) self.fields['person'].choices = persons_objects.Person.form_choices( predicate=lambda place, person: not person.has_building) def clean(self): person_id = int(self.cleaned_data['person']) x = int(self.cleaned_data['x']) y = int(self.cleaned_data['y']) person = persons_storage.persons[person_id] if (x, y) not in places_logic.get_available_positions( center_x=person.place.x, center_y=person.place.y): raise forms.ValidationError( 'Здание не может быть возведено на выбранных координатах') return self.cleaned_data
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)
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
class UserForm(BaseUserForm): new_place = fields.ChoiceField(label=u'Новый город') person = fields.ChoiceField(label=u'Мастер') def __init__(self, choosen_person_id, owner_id, *args, **kwargs): super(UserForm, self).__init__(*args, **kwargs) hero_id = heroes_logic.load_hero(account_id=owner_id).id self.fields['new_place'].choices = places_storage.places.get_choices() self.fields['person'].choices = persons_objects.Person.form_choices( choosen_person=persons_storage.persons.get(choosen_person_id), predicate=lambda place, person: person.politic_power. is_in_inner_circle(hero_id)) def clean_new_place(self): place_id = int(self.cleaned_data['new_place']) if len(places_storage.places[place_id].persons) >= c.PLACE_MAX_PERSONS: raise ValidationError( u'В городе достигнут максимум Мастеров. Чтобы переселить Мастера, необходимо кого-нибудь выселить.' ) return place_id def clean_person(self): person_id = int(self.cleaned_data['person']) person = persons_storage.persons[person_id] if person.has_building: raise ValidationError( u'У Мастера в собственности есть постройка. Прежде чем переехать он должен от неё избавиться.' ) if person.on_move_timeout: raise ValidationError( u'Мастер недавно переезжал. Должно пройти время, прежде чем он снова сможет переехать.' ) if len(person.place.persons) <= c.PLACE_MIN_PERSONS: raise ValidationError( u'В текущем городе Мастера слишком мало мастеров. Чтобы переселить Мастера, необходимо кого-нибудь вселить вместо него.' ) return person_id
class UserForm(BaseUserForm): place = fields.ChoiceField(label=u'Город') name = WordField(word_type=utg_relations.WORD_TYPE.NOUN, label=u'Название', skip_markers=(utg_relations.NOUN_FORM.COUNTABLE,)) def __init__(self, *args, **kwargs): super(UserForm, self).__init__(*args, **kwargs) self.fields['place'].choices = places_storage.places.get_choices()
class BaseForm(BaseUserForm): place = fields.ChoiceField(label='Город') power_bonus = fields.RelationField(label='Изменение влияния', relation=relations.POWER_BONUS_CHANGES) def __init__(self, *args, **kwargs): super(BaseForm, self).__init__(*args, **kwargs) self.fields['place'].choices = places_storage.places.get_choices()
class Person(forms.Form): value = fields.ChoiceField(label='Мастер') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['value'].choices = persons_objects.Person.form_choices() def get_card_data(self): return {'value': int(self.c.value)}
class BaseForm(BaseUserForm): person = fields.ChoiceField(label='Мастер') power_bonus = fields.RelationField(label='Изменение влияния', relation=relations.POWER_BONUS_CHANGES) def __init__(self, choosen_person_id, *args, **kwargs): super(BaseForm, self).__init__(*args, **kwargs) self.fields['person'].choices = persons_objects.Person.form_choices( choosen_person=persons_storage.persons.get(choosen_person_id))
class BaseForm(BaseUserForm): place = fields.ChoiceField(label='Город') new_description = bbcode.BBField( label='Новое описание', max_length=places_conf.settings.MAX_DESCRIPTION_LENGTH) def __init__(self, *args, **kwargs): super(BaseForm, self).__init__(*args, **kwargs) self.fields['place'].choices = places_storage.places.get_choices()
class Building(forms.Form): value = fields.ChoiceField(label='Строение') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['value'].choices = places_storage.buildings.get_choices() def get_card_data(self): return {'value': int(self.c.value)}
class BaseForm(BaseUserForm): person = fields.ChoiceField(label='Житель') name = WordField(word_type=utg_relations.WORD_TYPE.NOUN, label='Название', skip_markers=(utg_relations.NOUN_FORM.COUNTABLE, )) def __init__(self, choosen_person_id, *args, **kwargs): # pylint: disable=W0613 super(BaseForm, self).__init__(*args, **kwargs) self.fields['person'].choices = persons_objects.Person.form_choices( predicate=lambda place, person: not person.has_building)
class PersonForm(forms.Form): TEMPLATE = 'cards/person_form.html' person = fields.ChoiceField(label=u'Мастер') def __init__(self, *args, **kwargs): super(PersonForm, self).__init__(*args, **kwargs) self.fields['person'].choices = persons_objects.Person.form_choices() def get_card_data(self): return {'person_id': int(self.c.person)}
class EditThreadForm(forms.Form): caption = fields.CharField(label=u'Название', max_length=256, min_length=1) subcategory = fields.ChoiceField(label=u'Раздел', required=False) def __init__(self, subcategories, *args, **kwargs): super(EditThreadForm, self).__init__(*args, **kwargs) self.fields['subcategory'].choices = [(subcategory.id, subcategory.caption) for subcategory in subcategories]
class PlaceForm(forms.Form): TEMPLATE = 'cards/place_form.html' place = fields.ChoiceField(label=u'Город') def __init__(self, *args, **kwargs): super(PlaceForm, self).__init__(*args, **kwargs) self.fields['place'].choices = places_storage.places.get_choices() def get_card_data(self): return {'place_id': int(self.c.place)}
class BuildingForm(forms.Form): TEMPLATE = 'cards/building_form.html' building = fields.ChoiceField(label=u'Строение') def __init__(self, *args, **kwargs): super(BuildingForm, self).__init__(*args, **kwargs) self.fields['building'].choices = places_storage.buildings.get_choices() def get_card_data(self): return {'building_id': int(self.c.building)}
class PersonForm(forms.Form): TEMPLATE = 'cards/person_form.html' person = fields.ChoiceField(label=u'Советник') def __init__(self, *args, **kwargs): super(PersonForm, self).__init__(*args, **kwargs) self.fields['person'].choices = PersonPrototype.form_choices( only_weak=False) def get_card_data(self): return {'person_id': int(self.c.person)}
class BaseForm(BaseUserForm): place = fields.ChoiceField(label='Город') new_modifier = fields.TypedChoiceField(label='Новая специализация', choices=sorted( CITY_MODIFIERS.choices(), key=lambda g: g[1]), coerce=CITY_MODIFIERS.get_from_name) def __init__(self, *args, **kwargs): super(BaseForm, self).__init__(*args, **kwargs) self.fields['place'].choices = places_storage.places.get_choices()
class UserForm(BaseUserForm): person = fields.ChoiceField(label=u'Член Совета') power_bonus = fields.RelationField(label=u'Изменение бонуса влияния', relation=relations.POWER_BONUS_CHANGES) def __init__(self, choosen_person_id, *args, **kwargs): super(UserForm, self).__init__(*args, **kwargs) self.fields['person'].choices = PersonPrototype.form_choices( only_weak=False, choosen_person=persons_storage.get(choosen_person_id))
class BaseForm(BaseUserForm): person = fields.ChoiceField(label='Житель') def __init__(self, choosen_person_id, *args, **kwargs): # pylint: disable=W0613 super(BaseForm, self).__init__(*args, **kwargs) self.fields['person'].choices = persons_objects.Person.form_choices( predicate=self._person_has_building) @classmethod def _person_has_building(cls, place, person): # pylint: disable=W0613 return places_storage.buildings.get_by_person_id(person.id) is not None
class BaseForm(BaseUserForm): person_1 = fields.ChoiceField(label='Первый Мастер') person_2 = fields.ChoiceField(label='Второй Мастер') connection_type = fields.RelationField( label='Тип связи', relation=persons_relations.SOCIAL_CONNECTION_TYPE) def __init__(self, person_1_id, person_2_id, *args, **kwargs): super(BaseForm, self).__init__(*args, **kwargs) self.fields['person_1'].choices = persons_objects.Person.form_choices( choosen_person=persons_storage.persons.get(person_1_id), predicate=self.person_filter) self.fields['person_2'].choices = persons_objects.Person.form_choices( choosen_person=persons_storage.persons.get(person_2_id), predicate=self.person_filter) def person_filter(self, place, person): return not persons_storage.social_connections.connections_limit_reached( person) def clean(self): cleaned_data = super(BaseForm, self).clean() if 'person_1' not in cleaned_data or 'person_2' not in cleaned_data: return cleaned_data # error in one of that filed, no need to continue cleaning person_1 = persons_storage.persons[int(cleaned_data['person_1'])] person_2 = persons_storage.persons[int(cleaned_data['person_2'])] if person_1.id == person_2.id: raise ValidationError('Нужно выбрать разных Мастеров') if persons_storage.social_connections.is_connected(person_1, person_2): raise ValidationError('Мастера уже имеют социальную связь') if (persons_storage.social_connections.connections_limit_reached( person_1) or persons_storage.social_connections. connections_limit_reached(person_2)): raise ValidationError('Один из Мастеров уже имеет максимум связей') return cleaned_data
class BaseForm(BaseUserForm): person = fields.ChoiceField(label='Житель') name = WordField(word_type=utg_relations.WORD_TYPE.NOUN, label='Название', skip_markers=(utg_relations.NOUN_FORM.COUNTABLE, )) def __init__(self, choosen_person_id, *args, **kwargs): # pylint: disable=W0613 super(BaseForm, self).__init__(*args, **kwargs) self.fields['person'].choices = persons_objects.Person.form_choices( predicate=self._person_has_building) @classmethod def _person_has_building(cls, place, person): # pylint: disable=W0613 return places_storage.buildings.get_by_person_id(person.id) is not None
class UserForm(BaseUserForm): place = fields.ChoiceField(label=u'Город') conversion = fields.TypedChoiceField(label=u'Тип конверсии', choices=CONVERSION.choices(), coerce=CONVERSION.get_from_name) def __init__(self, *args, **kwargs): super(UserForm, self).__init__(*args, **kwargs) self.fields['place'].choices = places_storage.get_choices() def clean(self): cleaned_data = super(UserForm, self).clean() place = places_storage.get(int(cleaned_data['place'])) if (c.PLACE_MAX_BILLS_NUMBER <= len(resource_exchange_storage.get_exchanges_for_place(place)) ): raise ValidationError(u'Один город может поддерживать не более чем %(max_exchanges)d активных закона' % {'max_exchanges': c.PLACE_MAX_BILLS_NUMBER}) return cleaned_data
class EditItemForm(forms.Form): kit = fields.ChoiceField(label='Набор') caption = fields.CharField(label='Название', max_length=ItemPrototype.CAPTION_MAX_LENGTH, min_length=1) text = bbcode.BBField(label='Текст', min_length=1) def __init__(self, *args, **kwargs): super(EditItemForm, self).__init__(*args, **kwargs) self.fields['kit'].choices = kits_storage.get_form_choices() def clean_kit(self): kit_id = self.cleaned_data['kit'] kit = kits_storage[int(kit_id)] if kit is None: raise django_forms.ValidationError('Колекция не найдена') return kit