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.CheckboxInput(attrs=attrs), label=parameter.name, required=parameter.required, choices=parameter.choices, help_text=parameter.description)
class MigrateHostForm(forms.SelfHandlingForm): current_host = forms.CharField( label=_("Current Host"), required=False, widget=forms.TextInput(attrs={'readonly': 'readonly'})) migrate_type = forms.ChoiceField( label=_('Running Instance Migration Type'), choices=[('live_migrate', _('Live Migrate')), ('cold_migrate', _('Cold Migrate'))], widget=forms.ThemableSelectWidget(attrs={ 'class': 'switchable', 'data-slug': 'source' })) disk_over_commit = forms.BooleanField( label=_("Disk Over Commit"), initial=False, required=False, widget=forms.CheckboxInput( attrs={ 'class': 'switched', 'data-switch-on': 'source', 'data-source-live_migrate': _('Disk Over Commit') })) block_migration = forms.BooleanField( label=_("Block Migration"), initial=False, required=False, widget=forms.CheckboxInput( attrs={ 'class': 'switched', 'data-switch-on': 'source', 'data-source-live_migrate': _('Block Migration') })) def handle(self, request, data): try: current_host = data['current_host'] migrate_type = data['migrate_type'] disk_over_commit = data['disk_over_commit'] block_migration = data['block_migration'] live_migrate = migrate_type == 'live_migrate' api.nova.migrate_host(request, current_host, live_migrate=live_migrate, disk_over_commit=disk_over_commit, block_migration=block_migration) msg = _('Starting to migrate host: %(current)s') % \ {'current': current_host} messages.success(request, msg) return True except Exception: msg = _('Failed to migrate host "%s".') % data['current_host'] redirect = reverse('horizon:compute:hypervisor:index') exceptions.handle(request, message=msg, redirect=redirect) return False
class RulesConfigurationAction(workflows.Action): max_retries = forms.IntegerField(label=_("Max Retries"), initial=0, min_value=0, help_text=_( "In case of error, set the amount" " of retries for this job"), required=False) max_retries_interval = forms.IntegerField( label=_("Max Retries Interval"), initial=0, min_value=0, help_text=_("Set the interval between executions " "for retries in seconds"), required=False) mandatory = forms.BooleanField(label=_("Mandatory"), help_text=_("Set this action as mandatory"), widget=forms.CheckboxInput(), required=False) class Meta(object): name = _("Rules") help_text_template = "disaster_recovery/actions" \ "/_rules.html"
def __init__(self, request, context, *args, **kwargs): super(CreateRouterAssociationInfoAction, self).__init__(request, context, *args, **kwargs) # when an admin user uses the project panel BGPVPN, there is no # tenant_id in context because bgpvpn_get doesn't return it if request.user.is_superuser and context.get("project_id"): tenant_id = context.get("project_id") else: tenant_id = self.request.user.tenant_id try: routers = api.neutron.router_list(request, tenant_id=tenant_id) if routers: choices = [('', _("Choose a router"))] + [(r.id, r) for r in routers] self.fields['router_resource'].choices = choices else: self.fields['router_resource'].choices = [('', _("No router"))] except Exception: exceptions.handle(request, _("Unable to retrieve routers")) if api.neutron.is_extension_supported(request, 'bgpvpn-routes-control'): self.fields['with_parameters'] = forms.BooleanField( label=_("Optional parameters"), initial=False, required=False, widget=forms.CheckboxInput( attrs={ 'class': 'switchable', 'data-hide-tab': 'router_association__' 'add_router_parameters', 'data-hide-on-checked': 'false' }))
def build_interface_argument_fields(action, name, description, mapping_type, location, value_type, required, default_value): action.fields[name] = forms.CharField(label=_("Name"), widget=forms.TextInput(), required=True) action.fields[description] = forms.CharField(label=_("Description"), widget=forms.TextInput(), required=False) action.fields[mapping_type] = forms.ChoiceField( label=_("Mapping Type"), widget=forms.Select(), required=True, choices=[("args", _("Positional Argument")), ("configs", _("Configuration Value")), ("params", _("Named Parameter"))]) action.fields[location] = forms.CharField(label=_("Location"), widget=forms.TextInput(), required=True) action.fields[value_type] = forms.ChoiceField(label=_("Value Type"), widget=forms.Select(), required=True, choices=[ ("string", _("String")), ("number", _("Number")), ("data_source", _("Data Source")) ]) action.fields[required] = forms.BooleanField(widget=forms.CheckboxInput(), label=_("Required"), required=False, initial=True) action.fields[default_value] = forms.CharField(label=_("Default Value"), widget=forms.TextInput(), required=False)
def __init__(self, request, *args, **kwargs): super(GeneralConfigAction, self).__init__(request, *args, **kwargs) hlps = helpers.Helpers(request) plugin, hadoop_version = ( workflow_helpers.get_plugin_and_hadoop_version(request)) process_choices = [] try: version_details = saharaclient.plugin_get_version_details( request, plugin, hadoop_version) for service, processes in version_details.node_processes.items(): for process in processes: process_choices.append( (str(service) + ":" + str(process), process)) except Exception: exceptions.handle(request, _("Unable to generate process choices.")) if not saharaclient.SAHARA_AUTO_IP_ALLOCATION_ENABLED: pools = network.floating_ip_pools_list(request) pool_choices = [(pool.id, pool.name) for pool in pools] pool_choices.insert(0, (None, "Do not assign floating IPs")) self.fields['floating_ip_pool'] = forms.ChoiceField( label=_("Floating IP Pool"), choices=pool_choices, required=False) self.fields["autogroup"] = forms.BooleanField( label=_("Auto Security Group"), widget=forms.CheckboxInput(), help_text=_("Create security group for this Node Group."), required=False) groups = network.security_group_list(request) security_group_list = [(sg.id, sg.name) for sg in groups] self.fields["groups"] = forms.MultipleChoiceField( label=_("Security Groups"), widget=forms.CheckboxSelectMultiple(), help_text=_("Launch instances in these security groups."), choices=security_group_list, required=False) self.fields["processes"] = forms.MultipleChoiceField( label=_("Processes"), widget=forms.CheckboxSelectMultiple(), help_text=_("Processes to be launched in node group"), choices=process_choices) self.fields["plugin_name"] = forms.CharField( widget=forms.HiddenInput(), initial=plugin) self.fields["hadoop_version"] = forms.CharField( widget=forms.HiddenInput(), initial=hadoop_version) node_parameters = hlps.get_general_node_group_configs( plugin, hadoop_version) for param in node_parameters: self.fields[param.name] = workflow_helpers.build_control(param)
class GeneralConfigAction(workflows.Action): hidden_configure_field = forms.CharField( required=False, widget=forms.HiddenInput(attrs={"class": "hidden_configure_field"})) hidden_to_delete_field = forms.CharField( required=False, widget=forms.HiddenInput(attrs={"class": "hidden_to_delete_field"})) cluster_template_name = forms.CharField(label=_("Template Name")) description = forms.CharField(label=_("Description"), required=False, widget=forms.Textarea(attrs={'rows': 4})) use_autoconfig = forms.BooleanField( label=_("Auto-configure"), help_text=_("If selected, instances of a cluster will be " "automatically configured during creation. Otherwise you " "should manually specify configuration values"), required=False, widget=forms.CheckboxInput(), initial=True, ) anti_affinity = aa.anti_affinity_field() def __init__(self, request, *args, **kwargs): super(GeneralConfigAction, self).__init__(request, *args, **kwargs) plugin, hadoop_version = whelpers.\ get_plugin_and_hadoop_version(request) self.fields["plugin_name"] = forms.CharField( widget=forms.HiddenInput(), initial=plugin) self.fields["hadoop_version"] = forms.CharField( widget=forms.HiddenInput(), initial=hadoop_version) populate_anti_affinity_choices = aa.populate_anti_affinity_choices def get_help_text(self): extra = dict() plugin, hadoop_version = whelpers\ .get_plugin_and_hadoop_version(self.request) extra["plugin_name"] = plugin extra["hadoop_version"] = hadoop_version return super(GeneralConfigAction, self).get_help_text(extra) def clean(self): cleaned_data = super(GeneralConfigAction, self).clean() if cleaned_data.get("hidden_configure_field", None) \ == "create_nodegroup": self._errors = dict() return cleaned_data class Meta(object): name = _("Details") help_text_template = ("project/data_processing.cluster_templates/" "_configure_general_help.html")
def get_is_protected_form(object_type): return forms.BooleanField( label=_("Protected"), help_text=_("If selected, %s will be protected from modifications " "until this will be unselected") % object_type, required=False, widget=forms.CheckboxInput(), initial=False)
def __init__(self, request, *args, **kwargs): super(UpdateImageForm, self).__init__(request, *args, **kwargs) self.fields['disk_format'].choices = [(value, name) for value, name in IMAGE_FORMAT_CHOICES if value] if not policy.check((("image", "publicize_image"),), request): self.fields['public'].widget = forms.CheckboxInput( attrs={'readonly': 'readonly'})
def __init__(self, request, *args, **kwargs): super(CreateNetworkForm, self).__init__(request, *args, **kwargs) # self.fields['network_type'].choices = PROVIDER_TYPES if not policy.check((("network", "create_network:shared"), ), request): self.fields['shared'].widget = forms.CheckboxInput( attrs={'disabled': True}) self.fields['shared'].help_text = _( 'Non admin users are not allowed to set shared option.')
class UpdateDevice(forms.SelfHandlingForm): host_id = forms.CharField(label=_("host_id"), required=False, widget=forms.widgets.HiddenInput) uuid = forms.CharField(label=_("uuid"), required=False, widget=forms.widgets.HiddenInput) device_name = forms.CharField( label=_("Device Name"), required=False, widget=forms.TextInput(attrs={'readonly': 'readonly'})) pciaddr = forms.CharField( label=_("Device Address"), required=False, widget=forms.TextInput(attrs={'readonly': 'readonly'})) name = forms.CharField(label=_("Name"), required=False, widget=forms.TextInput()) enabled = forms.BooleanField(label=_("Enabled"), required=False, widget=forms.CheckboxInput()) failure_url = 'horizon:admin:inventory:detail' def clean(self): data = super(UpdateDevice, self).clean() if isinstance(data['enabled'], bool): data['enabled'] = 'True' if data['enabled'] else 'False' return data def handle(self, request, data): name = data['name'] uuid = data['uuid'] try: p = {} p['name'] = name p['enabled'] = str(data['enabled']) device = stx_api.sysinv.host_device_update(request, uuid, **p) msg = _('device "%s" was successfully updated.') % name LOG.debug(msg) messages.success(request, msg) return device except Exception as exc: msg = _('Failed to update device "%(n)s" (%(e)s).') % ({ 'n': name, 'e': exc }) LOG.info(msg) redirect = reverse(self.failure_url, args=[data['host_id']]) exceptions.handle(request, msg, redirect=redirect)
def __init__(self, request, *args, **kwargs): super(GeneralConfigAction, self).__init__(request, *args, **kwargs) hlps = helpers.Helpers(request) plugin, hadoop_version = ( workflow_helpers.get_plugin_and_hadoop_version(request)) process_choices = [] try: version_details = saharaclient.plugin_get_version_details( request, plugin, hadoop_version) for service, processes in version_details.node_processes.items(): for process in processes: process_choices.append( (str(service) + ":" + str(process), process)) except Exception: exceptions.handle(request, _("Unable to generate process choices.")) if not saharaclient.SAHARA_AUTO_IP_ALLOCATION_ENABLED: pools = network.floating_ip_pools_list(request) pool_choices = [(pool.id, pool.name) for pool in pools] pool_choices.insert(0, (None, "Do not assign floating IPs")) self.fields['floating_ip_pool'] = forms.ChoiceField( label=_("Floating IP Pool"), choices=pool_choices, required=False) self.fields["proxygateway"] = forms.BooleanField( label=_("Proxy Gateway"), widget=forms.CheckboxInput(), help_text=_("Sahara will use instances of this node group to " "access other cluster instances."), required=False) self.fields["processes"] = forms.MultipleChoiceField( label=_("Processes"), widget=forms.CheckboxSelectMultiple(), help_text=_("Processes to be launched in node group"), choices=process_choices) self.fields["plugin_name"] = forms.CharField( widget=forms.HiddenInput(), initial=plugin) self.fields["hadoop_version"] = forms.CharField( widget=forms.HiddenInput(), initial=hadoop_version) node_parameters = hlps.get_general_node_group_configs( plugin, hadoop_version) for param in node_parameters: self.fields[param.name] = workflow_helpers.build_control(param) if "guide_template_type" in request.resolver_match.kwargs: self.fields["guide_template_type"] = forms.CharField( required=False, widget=forms.HiddenInput(), initial=request.resolver_match.kwargs["guide_template_type"])
def get_is_public_form(object_type): return forms.BooleanField( label=_("Public"), help_text=_("If selected, %s will be shared across the " "tenants") % object_type, required=False, widget=forms.CheckboxInput(), initial=False, )
class UploadToImageForm(forms.SelfHandlingForm): name = forms.CharField(label=_('Volume Name'), widget=forms.TextInput( attrs={'readonly': 'readonly'})) image_name = forms.CharField(max_length=255, label=_('Image Name')) disk_format = forms.ChoiceField(label=_('Disk Format'), widget=forms.ThemableSelectWidget(), required=False) force = forms.BooleanField( label=pgettext_lazy("Force upload volume in in-use status to image", u"Force"), widget=forms.CheckboxInput(), required=False) def __init__(self, request, *args, **kwargs): super(UploadToImageForm, self).__init__(request, *args, **kwargs) # 'vhd','iso','aki','ari' and 'ami' disk formats are supported by # glance, but not by qemu-img. qemu-img supports 'vpc', 'cloop', 'cow' # and 'qcow' which are not supported by glance. # I can only use 'raw', 'vmdk', 'vdi' or 'qcow2' so qemu-img will not # have issues when processes image request from cinder. disk_format_choices = [(value, name) for value, name in IMAGE_FORMAT_CHOICES if value in VALID_DISK_FORMATS] self.fields['disk_format'].choices = disk_format_choices self.fields['disk_format'].initial = 'raw' if self.initial['status'] != 'in-use': self.fields['force'].widget = forms.widgets.HiddenInput() def handle(self, request, data): volume_id = self.initial['id'] try: # 'aki','ari','ami' container formats are supported by glance, # but they need matching disk format to use. # Glance usually uses 'bare' for other disk formats except # amazon's. Please check the comment in CreateImageForm class cinder.volume_upload_to_image(request, volume_id, data['force'], data['image_name'], DEFAULT_CONTAINER_FORMAT, data['disk_format']) message = _( 'Successfully sent the request to upload volume to image ' 'for volume: "%s"') % data['name'] messages.info(request, message) return True except Exception: redirect = reverse("horizon:project:volumes:index") error_message = _( 'Unable to upload volume to image for volume: "%s"') \ % data['name'] exceptions.handle(request, error_message, redirect=redirect)
class CreateNetworkInfoAction(workflows.Action): net_name = forms.CharField(max_length=255, label=_("Network Name"), required=False) admin_state = forms.BooleanField( label=_("Enable Admin State"), initial=True, required=False, help_text=_("The state to start the network in.")) shared = forms.BooleanField(label=_("Shared"), initial=False, required=False) with_subnet = forms.BooleanField(label=_("Create Subnet"), widget=forms.CheckboxInput(attrs={ 'class': 'switchable', 'data-slug': 'with_subnet', 'data-hide-tab': 'create_network__' 'createsubnetinfo' 'action,' 'create_network__' 'createsubnetdetail' 'action', 'data-hide-on-checked': 'false' }), initial=True, required=False) az_hints = forms.MultipleChoiceField( label=_("Availability Zone Hints"), required=False, help_text=_("Availability zones where the DHCP agents may be " "scheduled. Leaving this unset is equivalent to " "selecting all availability zones")) def __init__(self, request, *args, **kwargs): super(CreateNetworkInfoAction, self).__init__(request, *args, **kwargs) if not policy.check((("network", "create_network:shared"),), request): self.fields['shared'].widget = forms.HiddenInput() try: if api.neutron.is_extension_supported(request, 'network_availability_zone'): zones = api.neutron.list_availability_zones( self.request, 'network', 'available') self.fields['az_hints'].choices = [(zone['name'], zone['name']) for zone in zones] else: del self.fields['az_hints'] except Exception: msg = _('Failed to get availability zone list.') messages.warning(request, msg) del self.fields['az_hints'] class Meta(object): name = _("Network") help_text = _('Create a new network. ' 'In addition, a subnet associated with the network ' 'can be created in the following steps of this wizard.')
def __init__(self, request, *args, **kwargs): super(UpdateImageForm, self).__init__(request, *args, **kwargs) self.fields['disk_format'].choices = [(value, name) for value, name in IMAGE_FORMAT_CHOICES if value] if not policy.check((("image", "publicize_image"),), request): self.fields['public'].widget = forms.CheckboxInput( attrs={'readonly': 'readonly', 'disabled': 'disabled'}) self.fields['public'].help_text = _( 'Non admin users are not allowed to make images public.')
def __init__(self, request, *args, **kwargs): super(UpdateImageForm, self).__init__(request, *args, **kwargs) if not policy.check((("image", "publicize_image"), ), request): self.fields['public'].widget = forms.CheckboxInput( attrs={ 'readonly': 'readonly', 'disabled': 'disabled' }) self.fields['public'].help_text = _( 'Non admin users are not allowed to make images public.')
def __init__(self, request, *args, **kwargs): super(CreateNetworkInfoAction, self).__init__(request, *args, **kwargs) if api.neutron.is_port_profiles_supported(): self.fields['net_profile_id'].choices = ( self.get_network_profile_choices(request)) if not policy.check((("network", "create_network:shared"), ), request): self.fields['shared'].widget = forms.CheckboxInput( attrs={'disabled': True}) self.fields['shared'].help_text = _( 'Non admin users are not allowed to set shared option.')
def __init__(self, choices=()): widgets = [] for choice in choices: widgets.append(forms.CheckboxInput( attrs={ "label": choice[1], "value": choice[0], })) widgets.append(forms.TextInput()) widgets.append(forms.Select( choices=(("rw", _("Read/Write")), ("ro", _("Read only"))))) super(ShareWidget, self).__init__(widgets)
class SnapshotConfigurationAction(workflows.Action): snapshot = forms.BooleanField( label=_("Snapshot"), help_text=_("Use a LVM or Shadow Copy snapshot " "to have point in time consistent backups"), widget=forms.CheckboxInput(), initial=False, required=False) class Meta(object): name = _("Snapshot") help_text_template = "disaster_recovery/actions" \ "/_snapshot.html"
def __init__(self, request, *args, **kwargs): super(UpdatePortInfoAction, self).__init__(request, *args, **kwargs) try: if api.neutron.is_extension_supported(request, 'binding'): neutron_settings = getattr(settings, 'OPENSTACK_NEUTRON_NETWORK', {}) supported_vnic_types = neutron_settings.get( 'supported_vnic_types', ['*']) if supported_vnic_types: if supported_vnic_types == ['*']: vnic_type_choices = api.neutron.VNIC_TYPES else: vnic_type_choices = [ vnic_type for vnic_type in api.neutron.VNIC_TYPES if vnic_type[0] in supported_vnic_types ] self.fields['binding__vnic_type'] = ( forms.ThemableChoiceField( choices=vnic_type_choices, label=_("Binding: VNIC Type"), required=False)) except Exception: msg = _("Unable to verify the VNIC types extension in Neutron") exceptions.handle(self.request, msg) try: if api.neutron.is_extension_supported(request, 'mac-learning'): self.fields['mac_state'] = forms.BooleanField( label=_("MAC Learning State"), initial=False, required=False) except Exception: msg = _("Unable to retrieve MAC learning state") exceptions.handle(self.request, msg) try: if api.neutron.is_extension_supported(request, 'port-security'): self.fields['port_security_enabled'] = forms.BooleanField( label=_("Port Security"), required=False, widget=forms.CheckboxInput( attrs={ 'class': 'switchable', 'data-slug': 'port_security_enabled', 'data-hide-tab': 'update_port__update_security_groups', 'data-hide-on-checked': 'false' })) except Exception: msg = _("Unable to retrieve port security state") exceptions.handle(self.request, msg)
def _serialize_labels(self, prefix, prefix_trans, labels): for name, label in labels.items(): if not label['mutable']: continue res_name_translated = "%s: %s" % (six.text_type(prefix_trans), name) res_name = "label_%s%s" % (prefix, name) self.fields[res_name] = forms.BooleanField( label=res_name_translated, help_text=label['description'], widget=forms.CheckboxInput(), initial=label['status'], required=False, )
def __init__(self, request, *args, **kwargs): super(UpdateRule, self).__init__(request, *args, **kwargs) # Only admin user can update the 'shared' attribute self.ignore_shared = False if not policy.check( (("neutron-fwaas", "update_firewall_rule:shared"), ), request): self.fields['shared'].widget = forms.CheckboxInput( attrs={ 'readonly': 'readonly', 'disabled': 'disabled' }) self.fields['shared'].help_text = _( 'Non admin users are not allowed to set the shared property ' 'of the rule.') self.ignore_shared = True
class CreateNetworkInfoAction(workflows.Action): net_name = forms.CharField(max_length=255, label=_("Network Name"), required=False) admin_state = forms.ThemableChoiceField(choices=[(True, _('UP')), (False, _('DOWN'))], label=_("Admin State"), required=False, help_text=_("The state to start" " the network in.")) shared = forms.BooleanField(label=_("Shared"), initial=False, required=False) with_subnet = forms.BooleanField(label=_("Create Subnet"), widget=forms.CheckboxInput( attrs={ 'class': 'switchable', 'data-slug': 'with_subnet', 'data-hide-tab': 'create_network__' 'createsubnetinfo' 'action,' 'create_network__' 'createsubnetdetail' 'action', 'data-hide-on-checked': 'false' }), initial=True, required=False) def __init__(self, request, *args, **kwargs): super(CreateNetworkInfoAction, self).__init__(request, *args, **kwargs) if not policy.check((("network", "create_network:shared"), ), request): self.fields['shared'].widget = forms.HiddenInput() class Meta(object): name = _("Network") help_text = _('Create a new network. ' 'In addition, a subnet associated with the network ' 'can be created in the following steps of this wizard.')
class RunForm(forms.SelfHandlingForm): action_name = forms.CharField( label=_("Action"), required=True, widget=forms.TextInput(attrs={'readonly': 'readonly'})) input = forms.CharField(label=_("Input"), required=False, initial="{}", widget=forms.widgets.Textarea()) save_result = forms.CharField(label=_("Save result to DB"), required=False, widget=forms.CheckboxInput()) def handle(self, request, data): try: input = json.loads(data['input']) except Exception as e: msg = _('Action input is invalid JSON: %s') % str(e) messages.error(request, msg) return False try: params = {"save_result": data['save_result'] == 'True'} action = api.action_run(request, data['action_name'], input, params) msg = _('Run action has been created with name ' '"%s".') % action.name messages.success(request, msg) return True except Exception as e: # In case of a failure, keep the dialog open and show the error msg = _('Failed to run action "%(action_name)s"' ' %(e)s:') % { 'action_name': data['action_name'], 'e': str(e) } messages.error(request, msg) return False
def render(self, name, value, attrs=None, choices=()): if value is None: value = [] has_id = attrs and 'id' in attrs final_attrs = self.build_attrs(attrs, name=name) output = [] initial_service = uuid.uuid4() str_values = set([encoding.force_text(v) for v in value]) for i, (option_value, option_label) in enumerate( itertools.chain(self.choices, choices)): current_service = option_value.split(':')[0] if current_service != initial_service: if i > 0: output.append("</ul>") service_description = _("%s processes: ") % current_service service_description = html.conditional_escape( encoding.force_text(service_description)) output.append( "<label>{0}</label>".format(service_description)) initial_service = current_service output.append(encoding.force_text("<ul>")) if has_id: final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i)) label_for = ' for="%s"' % final_attrs['id'] else: label_for = '' cb = forms.CheckboxInput( final_attrs, check_test=lambda value: value in str_values) option_value = encoding.force_text(option_value) rendered_cb = cb.render(name, option_value) option_label = html.conditional_escape( encoding.force_text(option_label)) output.append( '<li><label{0}>{1} {2}</label></li>'.format( label_for, rendered_cb, option_label)) output.append('</ul>') return safestring.mark_safe('\n'.join(output))
def __init__(self, request, *args, **kwargs): super(SecurityConfigAction, self).__init__(request, *args, **kwargs) self.fields["security_autogroup"] = forms.BooleanField( label=_("Auto Security Group"), widget=forms.CheckboxInput(), help_text=_("Create security group for this Node Group."), required=False, initial=True) try: groups = neutron.security_group_list(request) except Exception: exceptions.handle(request, _("Unable to get security group list.")) raise security_group_list = [(sg.id, sg.name) for sg in groups] self.fields["security_groups"] = forms.MultipleChoiceField( label=_("Security Groups"), widget=forms.CheckboxSelectMultiple(), help_text=_("Launch instances in these security groups."), choices=security_group_list, required=False)
def __init__(self, request, *args, **kwargs): super(UpdateImageForm, self).__init__(request, *args, **kwargs) if not policy.check((("image", "publicize_image"),), request): self.fields['public'].widget = forms.CheckboxInput( attrs={'readonly': 'readonly'})
class AccountQuotaAction(workflows.Action): user_type = forms.ChoiceField( label=_("Account Type"), required=True, choices=[('normal', _("Normal User")), ('credit', _("Credit User"))], widget=forms.Select( attrs={ 'class': 'switchable', 'data-slug': 'user_type' } ) ) credit_line = forms.FloatField( label=_("Credit Line"), required=False, min_value=0.0, initial=settings.GIFT_BANLANCE, widget=forms.TextInput( attrs={ 'class': 'switched', 'data-switch-on': 'user_type', 'data-user_type-credit': _('Credit Line'), 'data-is-required': 'true', })) adjust_quota = forms.BooleanField( label=_("Adjust Quota"), required=False, initial=True, widget=forms.CheckboxInput( attrs={ 'class': 'switchable', 'data-slug': 'adjust_quota', 'data-hide-on-checked': 'false' } ) ) instances = forms.IntegerField(min_value=-1, initial=settings.QUOTA_DEFAULI['nova']['instances'], label=_("Instances"), required=True, widget=forms.TextInput(attrs={ 'class': 'switched', 'data-switch-on': 'adjust_quota', 'data-is-required': 'true', 'style': 'width 10%' })) cores = forms.IntegerField(min_value=2, initial=settings.QUOTA_DEFAULI['nova']['cores'], label=_("VCPUs"), required=True, widget=forms.TextInput(attrs={ 'class': 'switched', 'data-switch-on': 'adjust_quota', 'data-is-required': 'true' })) ram = forms.IntegerField(min_value=-1, initial=settings.QUOTA_DEFAULI['nova']['ram'], label=_("RAM (MB)"), required=True, widget=forms.TextInput(attrs={ 'class': 'switched', 'data-switch-on': 'adjust_quota', 'data-is-required': 'true' })) volumes = forms.IntegerField(min_value=-1, initial=settings.QUOTA_DEFAULI['cinder']['volumes'], label=_("Volumes"), required=True, widget=forms.TextInput(attrs={ 'class': 'switched', 'data-switch-on': 'adjust_quota', 'data-is-required': 'true' })) snapshots = forms.IntegerField(min_value=-1, initial=settings.QUOTA_DEFAULI['cinder']['snapshots'], label=_("Volume Snapshots"), required=True, widget=forms.TextInput(attrs={ 'class': 'switched', 'data-switch-on': 'adjust_quota', 'data-is-required': 'true' })) volume_gigabytes = forms.IntegerField( min_value=-1, initial=settings.QUOTA_DEFAULI['cinder']['volume_gigabytes'], label=_("Size of Volumes(GB)"), required=True, widget=forms.TextInput(attrs={ 'class': 'switched', 'data-switch-on': 'adjust_quota', 'data-is-required': 'true' })) snapshot_gigabytes = forms.IntegerField( min_value=-1, initial=settings.QUOTA_DEFAULI['cinder']['snapshot_gigabytes'], label=_("Size of Snapshots (GB)"), required=True, widget=forms.TextInput(attrs={ 'class': 'switched', 'data-switch-on': 'adjust_quota', 'data-is-required': 'true' })) floatingip = forms.IntegerField(min_value=-1, initial=settings.QUOTA_DEFAULI['neutron']['floatingip'], label=_("Floating IPs"), required=True, widget=forms.TextInput(attrs={ 'class': 'switched', 'data-switch-on': 'adjust_quota', 'data-is-required': 'true' })) network = forms.IntegerField(min_value=-1, initial=settings.QUOTA_DEFAULI['neutron']['network'], label=_("Networks"), required=True, widget=forms.TextInput(attrs={ 'class': 'switched', 'data-switch-on': 'adjust_quota', 'data-is-required': 'true' })) router = forms.IntegerField(min_value=-1, initial=settings.QUOTA_DEFAULI['neutron']['router'], label=_("Routers"), required=True, widget=forms.TextInput(attrs={ 'class': 'switched', 'data-switch-on': 'adjust_quota', 'data-is-required': 'true' })) subnet = forms.IntegerField(min_value=-1, initial=settings.QUOTA_DEFAULI['neutron']['subnet'], label=_("Subnets"), required=True, widget=forms.TextInput(attrs={ 'class': 'switched', 'data-switch-on': 'adjust_quota', 'data-is-required': 'true' })) pool = forms.IntegerField(min_value=-1, initial=settings.QUOTA_DEFAULI['neutron']['pool'], label=_("Loadbalancers"), required=True, widget=forms.TextInput(attrs={ 'class': 'switched', 'data-switch-on': 'adjust_quota', 'data-is-required': 'true' })) bandwidth = forms.IntegerField(required=False, widget=forms.HiddenInput, initial=settings.QUOTA_DEFAULI['neutron']['bandwidth'], ) def __init__(self, request, *args, **kwargs): super(AccountQuotaAction, self).__init__(request, *args, **kwargs) if policy.check((("identity", "project_admin_required"),), self.request): self.fields['credit_line'].validators.append(MaxValueValidator(settings.UPPER_CREDIT_LINE_FOR_PROJECT_ADMIN)) self.fields['credit_line'].help_text = _('credit line is between 0~%s') % settings.UPPER_CREDIT_LINE_FOR_PROJECT_ADMIN class Meta(object): name = _("Account Quota")
def __init__(self, request, *args, **kwargs): super(CreateServiceForm, self).__init__(request, *args, **kwargs) contract_type = NAL_CONSTRUCT_SERVICE_TYPE service_type_key = 'service_type_' + contract_type service_name = SERVICE_CREATE_COLUMNS['service_name'] service_type = SERVICE_CREATE_COLUMNS[service_type_key] self.fields['service_name'] = getattr(forms, service_name['field'])( label=service_name['label'], required=service_name['required']) self.fields['service_type'] = getattr(forms, service_type['field'])( label=service_type['label'], choices=service_type['choices'], required=service_type['required'], widget=forms.Select(attrs={ 'class': 'sub_switchable', 'id': 'service_type' })) for column in SERVICE_CREATE_COLUMNS['separate']: input_attrs = {} for input in DISPLAY_CREATE_COLUMNS_MAP[column[0]]: input_attrs['data-' + SERVICE_TYPE_MAP[input]] = \ column[1]['label'] input_attrs['class'] = 'switched' input_attrs['id'] = column[0] if column[1]['field'] == 'ChoiceField': self.fields[column[0]] = getattr(forms, column[1]['field'])( label=column[1]['label'], choices=column[1]['choices'], required=column[1]['required'], widget=forms.Select(attrs=input_attrs)) elif column[1]['field'] == 'BooleanField': self.fields[column[0]] = getattr(forms, column[1]['field'])( label=column[1]['label'], required=column[1]['required'], widget=forms.CheckboxInput(attrs=input_attrs)) else: self.fields[column[0]] = getattr(forms, column[1]['field'])( label=column[1]['label'], required=column[1]['required'], widget=forms.TextInput(attrs=input_attrs)) if 'IaaS_subnet_id' in self.fields: networks = _get_network_list(request) subnet_choices = [] for network_data in networks: subnets = _get_subnet_list(request, network_data.id) subnets = _get_filtering_subnet_list(subnets, 4) subnet_choices.extend([ (subnet_data.id, network_data.name + ': ' + subnet_data.cidr + ' (' + subnet_data.name + ')') for subnet_data in subnets ]) if subnet_choices: subnet_choices.insert(0, ("", _("Select subnet"))) self.fields['IaaS_subnet_id'].choices = subnet_choices else: messages.error(request, 'There are no selectable subnets.') raise exceptions.NotAvailable