class CategoryRoleForm(IndicoForm): name = StringField(_('Name'), [DataRequired()], description=_('The full name of the role')) code = StringField( _('Code'), [DataRequired(), Length(max=3)], filters=[lambda x: x.upper() if x else ''], render_kw={ 'style': 'width:60px; text-align:center; text-transform:uppercase;' }, description=_('A shortcut (max. 3 characters) for the role')) color = IndicoSinglePalettePickerField( _('Color'), color_list=get_role_colors(), text_color='ffffff', description=_('The color used when displaying the role')) def __init__(self, *args, **kwargs): self.role = kwargs.get('obj') self.category = kwargs.pop('category') super().__init__(*args, **kwargs) def validate_code(self, field): query = CategoryRole.query.with_parent( self.category).filter_by(code=field.data) if self.role is not None: query = query.filter(CategoryRole.id != self.role.id) if query.has_rows(): raise ValueError(_('A role with this code already exists.'))
def _get_color(self): used_colors = {role.color for role in self.category.roles} unused_colors = set(get_role_colors()) - used_colors return random.choice(tuple(unused_colors) or get_role_colors())