Python horizon.forms.Select() Examples

The following are 29 code examples of horizon.forms.Select(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module horizon.forms , or try the search function .
Example #1
Source File: create_instance.py    From trove-dashboard with Apache License 2.0 6 votes vote down vote up
def populate_config_choices(self, request, context):
        try:
            configs = api.trove.configuration_list(request)
            config_name = "%(name)s (%(datastore)s - %(version)s)"
            choices = [(c.id,
                        config_name % {'name': c.name,
                                       'datastore': c.datastore_name,
                                       'version': c.datastore_version_name})
                       for c in configs]
        except Exception:
            choices = []

        if choices:
            choices.insert(0, ("", _("Select configuration")))
        else:
            choices.insert(0, ("", _("No configurations available")))
        return choices 
Example #2
Source File: workflow_helpers.py    From avos with Apache License 2.0 6 votes vote down vote up
def _generate_plugin_version_fields(self, sahara):
        plugins = sahara.plugins.list()
        plugin_choices = [(plugin.name, plugin.title) for plugin in plugins]

        self.fields["plugin_name"] = forms.ChoiceField(
            label=_("Plugin Name"),
            choices=plugin_choices,
            widget=forms.Select(attrs={"class": "plugin_name_choice"}))

        for plugin in plugins:
            field_name = plugin.name + "_version"
            choice_field = forms.ChoiceField(
                label=_("Version"),
                choices=[(version, version) for version in plugin.versions],
                widget=forms.Select(
                    attrs={"class": "plugin_version_choice "
                                    + field_name + "_choice"})
            )
            self.fields[field_name] = choice_field 
Example #3
Source File: workflows.py    From avos with Apache License 2.0 6 votes vote down vote up
def populate_monitor_id_choices(self, request, context):
        self.fields['monitor_id'].label = (_("Select a health monitor of %s") %
                                           context['pool_name'])

        monitor_id_choices = [('', _("Select a Monitor"))]
        try:
            monitors = api.lbaas.pool_health_monitor_list(request)
            pool_monitors_ids = [pm.id for pm in context['pool_monitors']]
            for m in monitors:
                if m.id in pool_monitors_ids:
                    display_name = utils.get_monitor_display_name(m)
                    monitor_id_choices.append((m.id, display_name))
        except Exception:
            exceptions.handle(request,
                              _('Unable to retrieve monitors list.'))
        self.fields['monitor_id'].choices = monitor_id_choices

        return monitor_id_choices 
Example #4
Source File: workflows.py    From avos with Apache License 2.0 6 votes vote down vote up
def populate_monitor_id_choices(self, request, context):
        self.fields['monitor_id'].label = _("Select a monitor template "
                                            "for %s") % context['pool_name']

        monitor_id_choices = [('', _("Select a Monitor"))]
        try:
            tenant_id = self.request.user.tenant_id
            monitors = api.lbaas.pool_health_monitor_list(request,
                                                          tenant_id=tenant_id)
            pool_monitors_ids = [pm.id for pm in context['pool_monitors']]
            for m in monitors:
                if m.id not in pool_monitors_ids:
                    display_name = utils.get_monitor_display_name(m)
                    monitor_id_choices.append((m.id, display_name))
        except Exception:
            exceptions.handle(request,
                              _('Unable to retrieve monitors list.'))
        self.fields['monitor_id'].choices = monitor_id_choices

        return monitor_id_choices 
Example #5
Source File: workflows.py    From avos with Apache License 2.0 6 votes vote down vote up
def __init__(self, request, *args, **kwargs):
        super(AddVipAction, self).__init__(request, *args, **kwargs)
        tenant_id = request.user.tenant_id
        subnet_id_choices = [('', _("Select a Subnet"))]
        try:
            networks = api.neutron.network_list_for_tenant(request, tenant_id)
        except Exception:
            exceptions.handle(request,
                              _('Unable to retrieve networks list.'))
            networks = []
        for n in networks:
            for s in n['subnets']:
                subnet_id_choices.append((s.id, s.cidr))
        self.fields['subnet_id'].choices = subnet_id_choices
        protocol_choices = [('', _("Select a Protocol"))]
        [protocol_choices.append((p, p)) for p in AVAILABLE_PROTOCOLS]
        self.fields['protocol'].choices = protocol_choices

        session_persistence_choices = [('', _("No Session Persistence"))]
        for mode in ('SOURCE_IP', 'HTTP_COOKIE', 'APP_COOKIE'):
            session_persistence_choices.append((mode.lower(), mode))
        self.fields[
            'session_persistence'].choices = session_persistence_choices 
Example #6
Source File: create_instance.py    From avos with Apache License 2.0 6 votes vote down vote up
def populate_image_id_choices(self, request, context):
        choices = []
        images = image_utils.get_available_images(request,
                                                  context.get('project_id'),
                                                  self._images_cache)
        for image in images:
            image.bytes = image.size
            image.volume_size = max(
                image.min_disk, functions.bytes_to_gigabytes(image.bytes))
            choices.append((image.id, image))
            if context.get('image_id') == image.id and \
                    'volume_size' not in context:
                context['volume_size'] = image.volume_size
        if choices:
            choices.sort(key=lambda c: c[1].name)
            choices.insert(0, ("", _("Select Image")))
        else:
            choices.insert(0, ("", _("No images available")))
        return choices 
Example #7
Source File: create_instance.py    From avos with Apache License 2.0 6 votes vote down vote up
def populate_volume_id_choices(self, request, context):
        volumes = []
        try:
            if base.is_service_enabled(request, 'volume'):
                available = api.cinder.VOLUME_STATE_AVAILABLE
                volumes = [self._get_volume_display_name(v)
                           for v in cinder.volume_list(self.request,
                           search_opts=dict(status=available, bootable=1))]
        except Exception:
            exceptions.handle(self.request,
                              _('Unable to retrieve list of volumes.'))
        if volumes:
            volumes.insert(0, ("", _("Select Volume")))
        else:
            volumes.insert(0, ("", _("No volumes available")))
        return volumes 
Example #8
Source File: create_instance.py    From avos with Apache License 2.0 6 votes vote down vote up
def populate_volume_snapshot_id_choices(self, request, context):
        snapshots = []
        try:
            if base.is_service_enabled(request, 'volume'):
                available = api.cinder.VOLUME_STATE_AVAILABLE
                snapshots = [self._get_volume_display_name(s)
                             for s in cinder.volume_snapshot_list(
                             self.request, search_opts=dict(status=available))]
        except Exception:
            exceptions.handle(self.request,
                              _('Unable to retrieve list of volume '
                                'snapshots.'))
        if snapshots:
            snapshots.insert(0, ("", _("Select Volume Snapshot")))
        else:
            snapshots.insert(0, ("", _("No volume snapshots available")))
        return snapshots 
Example #9
Source File: forms.py    From monasca-ui with Apache License 2.0 6 votes vote down vote up
def set_notification_choices(self, request):
        try:
            notifications = api.monitor.notification_list(request)
        except Exception as e:
            notifications = []
            exceptions.handle(request,
                              _('Unable to retrieve notifications: %s') % e)
        notification_choices = [(notification['id'], notification['name'])
                                for notification in notifications]
        if notification_choices:
            if len(notification_choices) > 1:
                notification_choices.insert(
                    0, ("", six.text_type(_("Select Notification"))))
        else:
            notification_choices.insert(
                0, ("", six.text_type(_("No notifications available."))))

        self.fields['notifications'].choices = notification_choices 
Example #10
Source File: forms.py    From trove-dashboard with Apache License 2.0 6 votes vote down vote up
def _add_datastore_flavor_field(self,
                                    request,
                                    datastore,
                                    datastore_version):
        name = self._build_widget_field_name(datastore, datastore_version)
        attr_key = 'data-datastore-' + name
        field = forms.ChoiceField(
            label=_("Flavor"),
            help_text=_("Size of image to launch."),
            required=False,
            widget=forms.Select(attrs={
                'class': 'switched',
                'data-switch-on': 'datastore',
                attr_key: _("Flavor")
            }))
        valid_flavors = self.datastore_flavors(request,
                                               datastore,
                                               datastore_version)
        if valid_flavors:
            field.choices = instance_utils.sort_flavor_list(
                request, valid_flavors)

        return name, field 
Example #11
Source File: create_instance.py    From trove-dashboard with Apache License 2.0 6 votes vote down vote up
def _add_datastore_flavor_field(self,
                                    request,
                                    datastore,
                                    datastore_version):
        name = self._build_widget_field_name(datastore, datastore_version)
        attr_key = 'data-datastore-' + name
        field_name = self._build_flavor_field_name(datastore,
                                                   datastore_version)
        self.fields[field_name] = forms.ChoiceField(
            label=_("Flavor"),
            help_text=_("Size of image to launch."),
            required=False,
            widget=forms.Select(attrs={
                'class': 'switched',
                'data-switch-on': 'datastore',
                attr_key: _("Flavor")
            }))
        valid_flavors = self.datastore_flavors(request,
                                               datastore,
                                               datastore_version)
        if valid_flavors:
            self.fields[field_name].choices = instance_utils.sort_flavor_list(
                request, valid_flavors) 
Example #12
Source File: create_instance.py    From trove-dashboard with Apache License 2.0 6 votes vote down vote up
def populate_backup_choices(self, request, context):
        try:
            choices = []
            backups = api.trove.backup_list(request)
            for b in backups:
                if self.backup_id and b.id != self.backup_id:
                    continue
                if b.status == 'COMPLETED':
                    choices.append((b.id, b.name))
        except Exception:
            choices = []

        if choices:
            choices.insert(0, ("", _("Select backup")))
        else:
            choices.insert(0, ("", _("No backups available")))
        return choices 
Example #13
Source File: create_instance.py    From avos with Apache License 2.0 5 votes vote down vote up
def populate_keypair_choices(self, request, context):
        try:
            keypairs = api.nova.keypair_list(request)
            keypair_list = [(kp.name, kp.name) for kp in keypairs]
        except Exception:
            keypair_list = []
            exceptions.handle(request,
                              _('Unable to retrieve key pairs.'))
        if keypair_list:
            if len(keypair_list) == 1:
                self.fields['keypair'].initial = keypair_list[0][0]
            keypair_list.insert(0, ("", _("Select a key pair")))
        else:
            keypair_list = (("", _("No key pairs available")),)
        return keypair_list 
Example #14
Source File: create_instance.py    From avos with Apache License 2.0 5 votes vote down vote up
def get_policy_profile_choices(self, request):
        profile_choices = [('', _("Select a profile"))]
        for profile in self._get_profiles(request, 'policy'):
            profile_choices.append((profile.id, profile.name))
        return profile_choices 
Example #15
Source File: forms.py    From avos with Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(AttachForm, self).__init__(*args, **kwargs)

        # Hide the device field if the hypervisor doesn't support it.
        if not nova.can_set_mount_point():
            self.fields['device'].widget = forms.widgets.HiddenInput()

        # populate volume_id
        volume = kwargs.get('initial', {}).get("volume", None)
        if volume:
            volume_id = volume.id
        else:
            volume_id = None
        self.fields['volume_id'] = forms.CharField(widget=forms.HiddenInput(),
                                                   initial=volume_id)

        # Populate instance choices
        instance_list = kwargs.get('initial', {}).get('instances', [])
        instances = []
        for instance in instance_list:
            if instance.status in tables.VOLUME_ATTACH_READY_STATES and \
                    not any(instance.id == att["server_id"]
                            for att in volume.attachments):
                instances.append((instance.id, '%s (%s)' % (instance.name,
                                                            instance.id)))
        if instances:
            instances.insert(0, ("", _("Select an instance")))
        else:
            instances = (("", _("No instances available")),)
        self.fields['instance'].choices = instances 
Example #16
Source File: forms.py    From avos with Apache License 2.0 5 votes vote down vote up
def get_network_profile_choices(self, request):
        profile_choices = [('', _("Select a profile"))]
        for profile in self._get_profiles(request, 'network'):
            profile_choices.append((profile.id, profile.name))
        return profile_choices 
Example #17
Source File: create_instance.py    From avos with Apache License 2.0 5 votes vote down vote up
def __init__(self, request, context, *args, **kwargs):
        self._init_images_cache()
        self.request = request
        self.context = context
        super(SetInstanceDetailsAction, self).__init__(
            request, context, *args, **kwargs)

        # Hide the device field if the hypervisor doesn't support it.
        if not nova.can_set_mount_point():
            self.fields['device_name'].widget = forms.widgets.HiddenInput()

        source_type_choices = [
            ('', _("Select source")),
            ("image_id", _("Boot from image")),
            ("instance_snapshot_id", _("Boot from snapshot")),
        ]
        if base.is_service_enabled(request, 'volume'):
            source_type_choices.append(("volume_id", _("Boot from volume")))

            try:
                if api.nova.extension_supported("BlockDeviceMappingV2Boot",
                                                request):
                    source_type_choices.append(
                        ("volume_image_id",
                         _("Boot from image (creates a new volume)")))
            except Exception:
                exceptions.handle(request, _('Unable to retrieve extensions '
                                             'information.'))

            source_type_choices.append(
                ("volume_snapshot_id",
                 _("Boot from volume snapshot (creates a new volume)")))
        self.fields['source_type'].choices = source_type_choices 
Example #18
Source File: create.py    From avos with Apache License 2.0 5 votes vote down vote up
def __init__(self, request, *args, **kwargs):
        super(SelectPluginAction, self).__init__(request, *args, **kwargs)

        try:
            plugins = saharaclient.plugin_list(request)
        except Exception:
            plugins = []
            exceptions.handle(request,
                              _("Unable to fetch plugin list."))
        plugin_choices = [(plugin.name, plugin.title) for plugin in plugins]

        self.fields["plugin_name"] = forms.ChoiceField(
            label=_("Plugin name"),
            choices=plugin_choices,
            widget=forms.Select(attrs={"class": "plugin_name_choice"}))

        for plugin in plugins:
            field_name = plugin.name + "_version"
            choice_field = forms.ChoiceField(
                label=_("Version"),
                choices=[(version, version) for version in plugin.versions],
                widget=forms.Select(
                    attrs={"class": "plugin_version_choice "
                                    + field_name + "_choice"})
            )
            self.fields[field_name] = choice_field 
Example #19
Source File: forms.py    From avos with Apache License 2.0 5 votes vote down vote up
def get_tenant_choices(request):
    tenant_choices = [('', _("Select a project"))]
    tenants = []
    try:
        tenants, has_more = api.keystone.tenant_list(request)
    except Exception:
        msg = _('Projects could not be retrieved.')
        exceptions.handle(request, msg)
    for tenant in tenants:
        if tenant.enabled:
            tenant_choices.append((tenant.id, tenant.name))
    return tenant_choices 
Example #20
Source File: workflow_helpers.py    From avos with Apache License 2.0 5 votes vote down vote up
def build_control(parameter):
    attrs = {"priority": parameter.priority,
             "placeholder": parameter.default_value}
    if parameter.param_type == "string":
        return forms.CharField(
            widget=forms.TextInput(attrs=attrs),
            label=parameter.name,
            required=(parameter.required and
                      parameter.default_value is None),
            help_text=parameter.description,
            initial=parameter.initial_value)

    if parameter.param_type == "int":
        return forms.IntegerField(
            widget=forms.TextInput(attrs=attrs),
            label=parameter.name,
            required=parameter.required,
            help_text=parameter.description,
            initial=parameter.initial_value)

    elif parameter.param_type == "bool":
        return forms.BooleanField(
            widget=forms.CheckboxInput(attrs=attrs),
            label=parameter.name,
            required=False,
            initial=parameter.initial_value,
            help_text=parameter.description)

    elif parameter.param_type == "dropdown":
        return forms.ChoiceField(
            widget=forms.Select(attrs=attrs),
            label=parameter.name,
            required=parameter.required,
            choices=parameter.choices,
            help_text=parameter.description) 
Example #21
Source File: workflows.py    From avos with Apache License 2.0 5 votes vote down vote up
def __init__(self, request, *args, **kwargs):
        super(AddMemberAction, self).__init__(request, *args, **kwargs)

        pool_id_choices = [('', _("Select a Pool"))]
        try:
            tenant_id = self.request.user.tenant_id
            pools = api.lbaas.pool_list(request, tenant_id=tenant_id)
        except Exception:
            pools = []
            exceptions.handle(request,
                              _('Unable to retrieve pools list.'))
        pools = sorted(pools,
                       key=lambda pool: pool.name)
        for p in pools:
            pool_id_choices.append((p.id, p.name))
        self.fields['pool_id'].choices = pool_id_choices

        members_choices = []
        try:
            servers, has_more = api.nova.server_list(request)
        except Exception:
            servers = []
            exceptions.handle(request,
                              _('Unable to retrieve instances list.'))

        if len(servers) == 0:
            self.fields['members'].label = _(
                "No servers available. To add a member, you "
                "need at least one running instance.")
            self.fields['pool_id'].required = False
            self.fields['protocol_port'].required = False
            return

        for m in servers:
            members_choices.append((m.id, m.name))
        self.fields['members'].choices = sorted(
            members_choices,
            key=lambda member: member[1]) 
Example #22
Source File: forms.py    From tacker-horizon with Apache License 2.0 5 votes vote down vote up
def __init__(self, request, *args, **kwargs):
        super(DeployNS, self).__init__(request, *args, **kwargs)

        try:
            nsd_list = api.tacker.nsd_list(request)
            available_choices_nsd = [(ns['id'], ns['name']) for ns in
                                     nsd_list]
        except Exception as e:
            available_choices_nsd = []
            msg = _('Failed to retrieve available NS Catalog names: %s') % e
            LOG.error(msg)

        try:
            vim_list = api.tacker.vim_list(request)
            available_choices_vims = [(vim['id'], vim['name']) for vim in
                                      vim_list]

        except Exception as e:
            available_choices_vims = []
            msg = _('Failed to retrieve available VIM names: %s') % e
            LOG.error(msg)

        self.fields['nsd_id'].choices = [('', _('Select a NS Catalog Name'))
                                         ]+available_choices_nsd
        self.fields['vim_id'].choices = [('',
                                          _('Select a VIM Name'))
                                         ]+available_choices_vims 
Example #23
Source File: forms.py    From tacker-horizon with Apache License 2.0 5 votes vote down vote up
def __init__(self, request, *args, **kwargs):
        super(DeployVNF, self).__init__(request, *args, **kwargs)

        try:
            vnfd_list = api.tacker.vnfd_list(request,
                                             template_source='onboarded')
            available_choices_vnfd = [(vnf['id'], vnf['name']) for vnf in
                                      vnfd_list]
        except Exception as e:
            available_choices_vnfd = []
            msg = _('Failed to retrieve available VNF Catalog names: %s') % e
            LOG.error(msg)

        try:
            vim_list = api.tacker.vim_list(request)
            available_choices_vims = [(vim['id'], vim['name']) for vim in
                                      vim_list]

        except Exception as e:
            available_choices_vims = []
            msg = _('Failed to retrieve available VIM names: %s') % e
            LOG.error(msg)

        self.fields['vnfd_id'].choices = [('', _('Select a VNF Catalog Name'))
                                          ]+available_choices_vnfd
        self.fields['vim_id'].choices = [('',
                                          _('Select a VIM Name'))
                                         ]+available_choices_vims 
Example #24
Source File: forms.py    From manila-ui with Apache License 2.0 5 votes vote down vote up
def __init__(self, request, *args, **kwargs):
        super(Create, self).__init__(request, *args, **kwargs)
        self.neutron_enabled = base.is_service_enabled(request, 'network')
        net_choices = network.network_list(request)
        if self.neutron_enabled:
            self.fields['neutron_net_id'] = forms.ChoiceField(
                choices=[(' ', ' ')] + [(choice.id, choice.name_or_id)
                                        for choice in net_choices],
                label=_("Neutron Net"), widget=forms.Select(
                    attrs={'class': 'switchable', 'data-slug': 'net'}))
            for net in net_choices:
                # For each network create switched choice field with
                # the its subnet choices
                subnet_field_name = 'subnet-choices-%s' % net.id
                subnet_field = forms.ChoiceField(
                    choices=(), label=_("Neutron Subnet"),
                    widget=forms.Select(attrs={
                        'class': 'switched',
                        'data-switch-on': 'net',
                        'data-net-%s' % net.id: _("Neutron Subnet")
                    }))
                self.fields[subnet_field_name] = subnet_field
                subnet_choices = neutron.subnet_list(
                    request, network_id=net.id)
                self.fields[subnet_field_name].choices = [
                    (' ', ' ')] + [(choice.id, choice.name_or_id)
                                   for choice in subnet_choices]
        else:
            self.fields['nova_net_id'] = forms.ChoiceField(
                choices=[(' ', ' ')] + [(choice.id, choice.name_or_id)
                                        for choice in net_choices],
                label=_("Nova Net"), widget=forms.Select(
                    attrs={'class': 'switched', 'data-slug': 'net'})) 
Example #25
Source File: forms.py    From monasca-ui with Apache License 2.0 5 votes vote down vote up
def _init_fields(self, readOnly=False, create=False, initial=None):
        required = True
        textWidget = None
        textAreaWidget = forms.Textarea(attrs={'class': 'large-text-area'})
        choiceWidget = forms.Select
        if create:
            expressionWidget = SimpleExpressionWidget(initial)
            notificationWidget = NotificationCreateWidget()
        else:
            expressionWidget = textAreaWidget
            notificationWidget = NotificationCreateWidget()

        self.fields['name'] = forms.CharField(label=_("Name"),
                                              required=required,
                                              max_length=250,
                                              widget=textWidget)
        self.fields['expression'] = forms.CharField(label=_("Expression"),
                                                    required=required,
                                                    widget=expressionWidget)
        self.fields['description'] = forms.CharField(label=_("Description"),
                                                     required=False,
                                                     widget=textAreaWidget)
        sev_choices = [("LOW", _("Low")),
                       ("MEDIUM", _("Medium")),
                       ("HIGH", _("High")),
                       ("CRITICAL", _("Critical"))]
        self.fields['severity'] = forms.ChoiceField(label=_("Severity"),
                                                    choices=sev_choices,
                                                    widget=choiceWidget,
                                                    required=False)
        self.fields['state'] = forms.CharField(label=_("State"),
                                               required=False,
                                               widget=textWidget)
        self.fields['actions_enabled'] = \
            forms.BooleanField(label=_("Notifications Enabled"),
                               required=False,
                               initial=True)
        self.fields['notifications'] = NotificationField(
            label=_("Notifications"),
            required=False,
            widget=notificationWidget) 
Example #26
Source File: forms.py    From monasca-ui with Apache License 2.0 5 votes vote down vote up
def __init__(self, initial, attrs=None):
        comparators = [('>', '>'), ('>=', '>='), ('<', '<'), ('<=', '<=')]
        func = [('min', _('min')), ('max', _('max')), ('sum', _('sum')),
                ('count', _('count')), ('avg', _('avg'))]
        _widgets = (
            django_forms.widgets.Select(attrs=attrs, choices=func),
            ExpressionWidget(initial, attrs={}),
            django_forms.widgets.Select(attrs=attrs, choices=comparators),
            django_forms.widgets.TextInput(),
        )
        super(SimpleExpressionWidget, self).__init__(_widgets, attrs) 
Example #27
Source File: forms.py    From monasca-ui with Apache License 2.0 5 votes vote down vote up
def _init_fields(self, readOnly=False, create=False):
        required = True
        textWidget = None
        selectWidget = None
        readOnlyTextInput = READONLY_TEXTINPUT
        readOnlySelectInput = forms.Select(attrs={'disabled': 'disabled'})
        if readOnly:
            required = False
            textWidget = readOnlyTextInput
            selectWidget = readOnlySelectInput

        choices = [(n['type'], n['type'].capitalize()) for n in self.notification_types]
        choices = sorted(choices, key=lambda c: c[0])
        period_choices = [(0, '0'), (60, '60')]

        self.fields['name'] = forms.CharField(label=_("Name"),
                                              required=required,
                                              max_length="250",
                                              widget=textWidget,
                                              help_text=_("A descriptive name of "
                                                          "the notification method."))
        self.fields['type'] = forms.ChoiceField(
            label=_("Type"),
            required=required,
            widget=selectWidget,
            choices=choices,
            initial=constants.NotificationType.EMAIL,
            help_text=_("The type of notification method (i.e. email)."))
        self.fields['address'] = forms.CharField(label=_("Address"),
                                                 required=required,
                                                 max_length="512",
                                                 widget=textWidget,
                                                 help_text=_("The email/url address to notify."))
        self.fields['period'] = forms.ChoiceField(label=_("Period"),
                                                  widget=selectWidget,
                                                  choices=period_choices,
                                                  initial=0,
                                                  required=required,
                                                  help_text=_("The notification period.")) 
Example #28
Source File: create_instance.py    From trove-dashboard with Apache License 2.0 5 votes vote down vote up
def populate_master_choices(self, request, context):
        try:
            instances = self._get_instances()
            choices = sorted([(i.id, i.name) for i in
                             instances if i.status == 'ACTIVE'],
                             key=lambda i: i[1])
        except Exception:
            choices = []

        if choices:
            choices.insert(0, ("", _("Select instance")))
        else:
            choices.insert(0, ("", _("No instances available")))
        return choices 
Example #29
Source File: workflows.py    From avos with Apache License 2.0 4 votes vote down vote up
def __init__(self, request, *args, **kwargs):
        super(AddPoolAction, self).__init__(request, *args, **kwargs)

        tenant_id = request.user.tenant_id

        subnet_id_choices = [('', _("Select a Subnet"))]
        try:
            networks = api.neutron.network_list_for_tenant(request, tenant_id)
        except Exception:
            exceptions.handle(request,
                              _('Unable to retrieve networks list.'))
            networks = []
        for n in networks:
            for s in n['subnets']:
                subnet_id_choices.append((s.id, s.cidr))
        self.fields['subnet_id'].choices = subnet_id_choices

        protocol_choices = [('', _("Select a Protocol"))]
        [protocol_choices.append((p, p)) for p in AVAILABLE_PROTOCOLS]
        self.fields['protocol'].choices = protocol_choices

        lb_method_choices = [('', _("Select a Method"))]
        [lb_method_choices.append((m, m)) for m in AVAILABLE_METHODS]
        self.fields['lb_method'].choices = lb_method_choices

        # provider choice
        try:
            if api.neutron.is_extension_supported(request, 'service-type'):
                provider_list = api.neutron.provider_list(request)
                providers = [p for p in provider_list
                             if p['service_type'] == 'LOADBALANCER']
            else:
                providers = None
        except Exception:
            exceptions.handle(request,
                              _('Unable to retrieve providers list.'))
            providers = []

        if providers:
            default_providers = [p for p in providers if p.get('default')]
            if default_providers:
                default_provider = default_providers[0]['name']
            else:
                default_provider = None
            provider_choices = [(p['name'], p['name']) for p in providers
                                if p['name'] != default_provider]
            if default_provider:
                provider_choices.insert(
                    0, (default_provider,
                        _("%s (default)") % default_provider))
        else:
            if providers is None:
                msg = _("Provider for Load Balancer is not supported")
            else:
                msg = _("No provider is available")
            provider_choices = [('', msg)]
            self.fields['provider'].widget.attrs['readonly'] = True
        self.fields['provider'].choices = provider_choices