def __init__(self, *args, **kwargs): super(SettingsForm, self).__init__(*args, **kwargs) self.instance._original_stg_guiprotocol = self.instance.stg_guiprotocol self.instance._original_stg_guiaddress = self.instance.stg_guiaddress self.instance._original_stg_guiport = self.instance.stg_guiport self.instance._original_stg_guihttpsport = self.instance.stg_guihttpsport self.instance._original_stg_guihttpsredirect = self.instance.stg_guihttpsredirect self.instance._original_stg_syslogserver = ( self.instance.stg_syslogserver ) self.instance._original_stg_directoryservice = ( self.instance.stg_directoryservice ) self.fields['stg_language'].choices = settings.LANGUAGES self.fields['stg_language'].label = _("Language (Require UI reload)") self.fields['stg_guiaddress'] = forms.ChoiceField( label=self.fields['stg_guiaddress'].label ) self.fields['stg_guiaddress'].choices = [ ['0.0.0.0', '0.0.0.0'] ] + list(choices.IPChoices(ipv6=False)) self.fields['stg_guiv6address'] = forms.ChoiceField( label=self.fields['stg_guiv6address'].label ) self.fields['stg_guiv6address'].choices = [ ['::', '::'] ] + list(choices.IPChoices(ipv4=False))
class ZFSDataset_CreateForm(Form): dataset_name = forms.CharField(max_length=128, label=_('Dataset Name')) dataset_compression = forms.ChoiceField( choices=choices.ZFS_CompressionChoices, widget=forms.Select(attrs=attrs_dict), label=_('Compression level')) dataset_atime = forms.ChoiceField( choices=choices.ZFS_AtimeChoices, widget=forms.RadioSelect(attrs=attrs_dict), label=_('Enable atime')) dataset_refquota = forms.CharField(max_length=128, initial=0, label=_('Quota for this dataset'), help_text=_('0=Unlimited; example: 1g')) dataset_quota = forms.CharField( max_length=128, initial=0, label=_('Quota for this dataset and all children'), help_text=_('0=Unlimited; example: 1g')) dataset_refreserv = forms.CharField( max_length=128, initial=0, label=_('Reserved space for this dataset'), help_text=_('0=None; example: 1g')) dataset_reserv = forms.CharField( max_length=128, initial=0, label=_('Reserved space for this dataset and all children'), help_text=_('0=None; example: 1g')) def __init__(self, *args, **kwargs): self.fs = kwargs.pop('fs') super(ZFSDataset_CreateForm, self).__init__(*args, **kwargs) def clean_dataset_name(self): name = self.cleaned_data["dataset_name"] if not re.search(r'^[a-zA-Z0-9][a-zA-Z0-9_\-:.]*$', name): raise forms.ValidationError( _("Dataset names must begin with an " "alphanumeric character and may only contain " "\"-\", \"_\", \":\" and \".\".")) return name def clean(self): cleaned_data = _clean_quota_fields( self, ('refquota', 'quota', 'reserv', 'refreserv'), "dataset_") full_dataset_name = "%s/%s" % (self.fs, cleaned_data.get("dataset_name")) if len(zfs.list_datasets(path=full_dataset_name)) > 0: msg = _(u"You already have a dataset with the same name") self._errors["dataset_name"] = self.error_class([msg]) del cleaned_data["dataset_name"] return cleaned_data def set_error(self, msg): msg = u"%s" % msg self._errors['__all__'] = self.error_class([msg]) del self.cleaned_data
class ZFSDataset_EditForm(Form): dataset_compression = forms.ChoiceField( choices=choices.ZFS_CompressionChoices, widget=forms.Select(attrs=attrs_dict), label=_('Compression level')) dataset_atime = forms.ChoiceField( choices=choices.ZFS_AtimeChoices, widget=forms.RadioSelect(attrs=attrs_dict), label=_('Enable atime')) dataset_refquota = forms.CharField(max_length=128, initial=0, label=_('Quota for this dataset'), help_text=_('0=Unlimited; example: 1g')) dataset_quota = forms.CharField( max_length=128, initial=0, label=_('Quota for this dataset and all children'), help_text=_('0=Unlimited; example: 1g')) dataset_refreservation = forms.CharField( max_length=128, initial=0, label=_('Reserved space for this dataset'), help_text=_('0=None; example: 1g')) dataset_reservation = forms.CharField( max_length=128, initial=0, label=_('Reserved space for this dataset and all children'), help_text=_('0=None; example: 1g')) def __init__(self, *args, **kwargs): self._fs = kwargs.pop("fs", None) super(ZFSDataset_EditForm, self).__init__(*args, **kwargs) data = notifier().zfs_get_options(self._fs) self.fields['dataset_compression'].initial = data['compression'] self.fields['dataset_atime'].initial = data['atime'] for attr in ('refquota', 'quota', 'reservation', 'refreservation'): formfield = 'dataset_%s' % (attr) if data[attr] == 'none': self.fields[formfield].initial = 0 else: self.fields[formfield].initial = data[attr] def clean(self): return _clean_quota_fields( self, ('refquota', 'quota', 'reservation', 'refreservation'), "dataset_") def set_error(self, msg): msg = u"%s" % msg self._errors['__all__'] = self.error_class([msg]) del self.cleaned_data
class FirmwareTemporaryLocationForm(Form): mountpoint = forms.ChoiceField( label=_("Place to temporarily place firmware file"), help_text=_("The system will use this place to temporarily store the " "firmware file before it's being applied."), choices=(), widget=forms.Select(attrs={'class': 'required'}), ) def clean_mountpoint(self): mp = self.cleaned_data.get("mountpoint") if mp.startswith('/'): clean_path_execbit(mp) clean_path_locked(mp) return mp def __init__(self, *args, **kwargs): super(FirmwareTemporaryLocationForm, self).__init__(*args, **kwargs) self.fields['mountpoint'].choices = [ (x.mp_path, x.mp_path) for x in MountPoint.objects.exclude(mp_volume__vol_fstype='iscsi') ] self.fields['mountpoint'].choices.append( (':temp:', _('Memory device'))) def done(self, *args, **kwargs): mp = str(self.cleaned_data["mountpoint"]) if mp == ":temp:": notifier().create_upload_location() else: notifier().change_upload_location(mp)
def __init__(self, *args, **kwargs): self.jail = None if kwargs and 'jail' in kwargs: self.jail = kwargs.pop('jail') super(NullMountPointForm, self).__init__(*args, **kwargs) if kwargs and 'instance' in kwargs: self.instance = kwargs.pop('instance') if not self.jail: self.jail = Jails.objects.filter( jail_host=self.instance.jail)[0] self.jc = JailsConfiguration.objects.order_by("-id")[0] self.fields['jail'] = forms.ChoiceField( label=_("Jail"), choices=(), widget=forms.Select(attrs={'class': 'required'}), ) if self.jail: self.fields['jail'].initial = self.jail.jail_host self.fields['jail'].widget.attrs['readonly'] = True try: clean_path_execbit(self.jc.jc_path) except forms.ValidationError, e: self.errors['__all__'] = self.error_class(e.messages)
class LAGGInterfaceMemberForm(ModelForm): lagg_physnic = forms.ChoiceField(label=_("LAGG Physical NIC")) class Meta: fields = '__all__' model = models.LAGGInterfaceMembers def __init__(self, *args, **kwargs): super(LAGGInterfaceMemberForm, self).__init__(*args, **kwargs) if self.instance.id: self.fields['lagg_interfacegroup'].widget.attrs['readonly'] = True self.fields['lagg_interfacegroup'].widget.attrs['class'] = ( 'dijitDisabled dijitSelectDisabled') self.fields['lagg_physnic'].widget.attrs['readonly'] = True self.fields['lagg_physnic'].widget.attrs['class'] = ( 'dijitDisabled dijitSelectDisabled') self.fields['lagg_physnic'].choices = (( self.instance.lagg_physnic, self.instance.lagg_physnic), ) else: self.fields['lagg_physnic'].choices = list( choices.NICChoices(nolagg=True, novlan=True)) def delete(self, *args, **kwargs): with DBSync(): super(LAGGInterfaceMemberForm, self).delete(*args, **kwargs) notifier().start("network") def save(self, *args, **kwargs): with DBSync(): return super(LAGGInterfaceMemberForm, self).save(*args, **kwargs) def done(self, *args, **kwargs): super(LAGGInterfaceMemberForm, self).done(*args, **kwargs) notifier().start("network")
def __init__(self, *args, **kwargs): self.jail = None if kwargs and kwargs.has_key('jail'): self.jail = kwargs.pop('jail') super(MkdirForm, self).__init__(*args, **kwargs) if self.jail: self.jc = JailsConfiguration.objects.order_by("-id")[0] jail_path = "%s/%s" % (self.jc.jc_path, self.jail.jail_host) self.fields['path'].widget.attrs['root'] = (jail_path) self.fields['jail'].initial = self.jail.jail_host self.fields['jail'].widget.attrs = { 'readonly': True, 'class': ( 'dijitDisabled dijitTextBoxDisabled' 'dijitValidationTextBoxDisabled' ), } else: self.fields['jail'] = forms.ChoiceField( label=_("Jail"), choices=(), widget=forms.Select(attrs={'class': 'required'}), ) pjlist = [] wlist = Warden().list() for wj in wlist: if wj[WARDEN_KEY_STATUS] == WARDEN_STATUS_RUNNING: pjlist.append(wj[WARDEN_KEY_HOST]) self.fields['jail'].choices = [(pj, pj) for pj in pjlist ]
def __init__(self, *args, **kwargs): super(iSCSITargetPortalIPForm, self).__init__(*args, **kwargs) self.fields['iscsi_target_portalip_ip'] = forms.ChoiceField( label=self.fields['iscsi_target_portalip_ip'].label, ) ips = [('', '------'), ('0.0.0.0', '0.0.0.0')] iface_ips = { iface.int_vip: f'{iface.int_ipv4address}, {iface.int_ipv4address_b}' for iface in Interfaces.objects.exclude( Q(int_vip=None) | Q(int_vip='')) } for alias in Alias.objects.exclude( Q(alias_vip=None) | Q(alias_vip='')): iface_ips[ alias. alias_vip] = f'{alias.alias_v4address}, {alias.alias_v4address_b}' for k, v in choices.IPChoices(): if v in iface_ips: v = iface_ips[v] ips.append((k, v)) self.fields['iscsi_target_portalip_ip'].choices = ips if not self.instance.id and not self.data: if not (self.parent and self.parent.instance.id and self.parent.instance.ips.all().count() > 0) or ( self.parent and not self.parent.instance.id): self.fields['iscsi_target_portalip_ip'].initial = '0.0.0.0'
class PBIUploadForm(Form): pbifile = FileField(label=_("PBI file to be installed"), required=True) pjail = forms.ChoiceField( label=_("Plugin Jail"), help_text=_("The plugin jail that the PBI is to be installed in."), choices=(), widget=forms.Select(attrs={'class': 'required'}), ) def __init__(self, *args, **kwargs): self.jail = None if kwargs and kwargs.has_key('jail'): self.jail = kwargs.pop('jail') super(PBIUploadForm, self).__init__(*args, **kwargs) if not self.jail: jc = JailsConfiguration.objects.order_by("-id")[0] try: clean_path_execbit(jc.jc_path) except forms.ValidationError, e: self.errors['__all__'] = self.error_class(e.messages) pjlist = [] wlist = Warden().list() for wj in wlist: if wj[WARDEN_KEY_TYPE] == WARDEN_TYPE_PLUGINJAIL and \ wj[WARDEN_KEY_STATUS] == WARDEN_STATUS_RUNNING: pjlist.append(wj[WARDEN_KEY_HOST]) self.fields['pjail'].choices = [(pj, pj) for pj in pjlist] else:
class JailImportForm(Form): jail_path = PathField( label=_("Plugins jail path"), required=True, ) jail_ipv4address = IP4AddressFormField( label=_("Jail IPv4 Address"), required=True, ) jail_ipv4netmask = forms.ChoiceField( label=_("Jail IPv4 Netmask"), initial="24", choices=choices.v4NetmaskBitList, required=True, ) plugins_path = PathField( label=_("Plugins archive Path"), required=True, ) def __init__(self, *args, **kwargs): super(JailImportForm, self).__init__(*args, **kwargs) def clean_jail_ipv4address(self): return _clean_jail_ipv4address( self.cleaned_data.get("jail_ipv4address"))
def __init__(self, *args, **kwargs): super(IPMIForm, self).__init__(*args, **kwargs) self.fields['dhcp'].widget.attrs['onChange'] = ( 'javascript:toggleGeneric(' '"id_dhcp", ["id_ipv4address", "id_ipv4netmaskbit"]);') channels = [] _n = notifier() for i in range(1, 17): try: data = _n.ipmi_get_lan(channel=i) except: continue if not data: continue channels.append((i, i)) self.fields['channel'] = forms.ChoiceField( choices=channels, label=_('Channel'), ) self.fields.keyOrder.remove('channel') self.fields.keyOrder.insert(0, 'channel')
class PBITemporaryLocationForm(Form): mountpoint = forms.ChoiceField( label=_("Place to temporarily place PBI file"), help_text=_("The system will use this place to temporarily store the " "PBI file before it's installed."), choices=(), widget=forms.Select(attrs={'class': 'required'}), ) def __init__(self, *args, **kwargs): super(PBITemporaryLocationForm, self).__init__(*args, **kwargs) mp = PluginsJail.objects.order_by("-id") if mp and notifier().plugins_jail_configured(): mp = mp[0] self.fields['mountpoint'].choices = [ (mp.plugins_path, mp.plugins_path), ] else: self.fields['mountpoint'].choices = [(x.mp_path, x.mp_path) \ for x in MountPoint.objects.exclude( mp_volume__vol_fstype='iscsi')] def done(self, *args, **kwargs): notifier().change_upload_location( self.cleaned_data["mountpoint"].__str__())
def __init__(self, *args, **kwargs): super(UPSForm, self).__init__(*args, **kwargs) _n = notifier() if not _n.is_freenas(): self.fields['ups_powerdown'].help_text = _( "Signal the UPS to power off after TrueNAS shuts down.") self.fields['ups_shutdown'].widget.attrs['onChange'] = mark_safe( "disableGeneric('id_ups_shutdown', ['id_ups_shutdowntimer'], " "function(box) { if(box.get('value') == 'lowbatt') { return true; " "} else { return false; } });") self.fields['ups_mode'].widget.attrs['onChange'] = "upsModeToggle();" if self.instance.id and self.instance.ups_shutdown == 'lowbatt': self.fields['ups_shutdowntimer'].widget.attrs['class'] = ( 'dijitDisabled dijitTextBoxDisabled ' 'dijitValidationTextBoxDisabled') self.fields['ups_port'] = forms.ChoiceField( label=_("Port"), required=False, ) self.fields['ups_port'].widget = forms.widgets.ComboBox() self.fields['ups_port'].choices = choices.UPS_PORT_CHOICES() if self.data and self.data.get("ups_port"): self.fields['ups_port'].choices.insert( 0, (self.data.get("ups_port"), self.data.get("ups_port"))) elif self.instance.id: self.fields['ups_port'].choices.insert( 0, (self.instance.ups_port, self.instance.ups_port))
def __init__(self, *args, **kwargs): self.jail = None if kwargs and 'jail' in kwargs: self.jail = kwargs.pop('jail') super(JailMountPointForm, self).__init__(*args, **kwargs) self._full = None if kwargs and 'instance' in kwargs: self.instance = kwargs.pop('instance') if not self.jail and self.instance.id: try: self.jail = Jails.objects.filter( jail_host=self.instance.jail )[0] except: pass self.jc = JailsConfiguration.objects.order_by("-id")[0] self.fields['jail'] = forms.ChoiceField( label=_("Jail"), choices=(), widget=forms.Select(attrs={'class': 'required'}), ) if self.jail: self.fields['jail'].initial = self.jail.jail_host self.fields['jail'].widget.attrs['readonly'] = True jail_path = "%s/%s" % (self.jc.jc_path, self.jail.jail_host) self.fields['destination'].widget.attrs['root'] = jail_path try: clean_path_execbit(self.jc.jc_path) except forms.ValidationError as e: self.errors['__all__'] = self.error_class(e.messages) pjlist = [] try: wlist = Warden().cached_list() except: wlist = [] for wj in wlist: pjlist.append(wj[WARDEN_KEY_HOST]) self.fields['jail'].choices = [('', '')] + [(pj, pj) for pj in pjlist] self.fields['jail'].widget.attrs['onChange'] = ( 'addStorageJailChange(this);' ) self.fields['mpjc_path'].widget = forms.widgets.HiddenInput() self.fields['mpjc_path'].initial = self.jc.jc_path if self.instance.id: self.fields['mounted'].initial = self.instance.mounted else: self.fields['mounted'].widget = forms.widgets.HiddenInput()
class VLANForm(ModelForm): vlan_pint = forms.ChoiceField(label=_("Parent Interface")) class Meta: fields = '__all__' model = models.VLAN def __init__(self, *args, **kwargs): super(VLANForm, self).__init__(*args, **kwargs) self.fields['vlan_pint'].choices = list( choices.NICChoices(novlan=True, exclude_configured=False) ) def clean_vlan_vint(self): name = self.cleaned_data['vlan_vint'] reg = re.search(r'^vlan(?P<num>\d+)$', name) if not reg: raise forms.ValidationError( _("The name must be vlanX where X is a number. Example: vlan0") ) return "vlan%d" % (int(reg.group("num")), ) def clean_vlan_tag(self): tag = self.cleaned_data['vlan_tag'] if tag > 4095 or tag < 1: raise forms.ValidationError(_("VLAN Tags are 1 - 4095 inclusive")) return tag def save(self): vlan_pint = self.cleaned_data['vlan_pint'] vlan_vint = self.cleaned_data['vlan_vint'] with DBSync(): if len(models.Interfaces.objects.filter(int_interface=vlan_pint)) == 0: vlan_interface = models.Interfaces( int_interface=vlan_pint, int_name=vlan_pint, int_dhcp=False, int_ipv6auto=False, int_options='up', ) vlan_interface.save() models.Interfaces.objects.create( int_interface=vlan_vint, int_name=vlan_vint, int_dhcp=False, int_ipv6auto=False, ) return super(VLANForm, self).save() def delete(self, *args, **kwargs): with DBSync(): super(VLANForm, self).delete(*args, **kwargs) notifier().start("network") def done(self, *args, **kwargs): super(VLANForm, self).done(*args, **kwargs) notifier().start("network")
def __init__(self, *args, **kwargs): super(iSCSITargetExtentForm, self).__init__(*args, **kwargs) key_order(self, 1, 'iscsi_target_extent_type', instance=True) if not self._api: self.fields['iscsi_target_extent_disk'] = forms.ChoiceField( choices=(), widget=forms.Select(attrs={'maxHeight': 200}), label=_('Device'), required=False, ) else: self.fields['iscsi_target_extent_disk'] = forms.CharField( required=False, ) key_order(self, 2, 'iscsi_target_extent_disk', instance=True) if self.instance.id: with client as c: e = self.instance.iscsi_target_extent_path exclude = [e] if not self._api else [] disk_choices = list(c.call( 'iscsi.extent.disk_choices', exclude ).items()) disk_choices.sort(key=lambda x: x[1]) if self.instance.iscsi_target_extent_type == 'File': self.fields['iscsi_target_extent_type'].initial = 'File' else: self.fields['iscsi_target_extent_type'].initial = 'Disk' if not self._api: self.fields['iscsi_target_extent_disk'].choices = disk_choices if self.instance.iscsi_target_extent_type in ('ZVOL', 'HAST'): self.fields['iscsi_target_extent_disk'].initial = disk_choices else: self.fields['iscsi_target_extent_disk'].initial = self.instance.get_device()[5:] self._path = self.instance.iscsi_target_extent_path self._name = self.instance.iscsi_target_extent_name elif not self._api: with client as c: disk_choices = list(c.call( 'iscsi.extent.disk_choices' ).items()) disk_choices.sort(key=lambda x: x[1]) self.fields['iscsi_target_extent_disk'].choices = disk_choices self.fields['iscsi_target_extent_type'].widget.attrs['onChange'] = "iscsiExtentToggle();extentZvolToggle();" self.fields['iscsi_target_extent_path'].required = False self.fields['iscsi_target_extent_disk'].widget.attrs['onChange'] = ( 'extentZvolToggle();' )
class IPMIForm(Form): # Max password length via IPMI v2.0 is 20 chars. We only support IPMI # v2.0+ compliant boards thus far. ipmi_password1 = forms.CharField(label=_("Password"), max_length=20, widget=forms.PasswordInput, required=False) ipmi_password2 = forms.CharField( label=_("Password confirmation"), max_length=20, widget=forms.PasswordInput, help_text=_("Enter the same password as above, for verification."), required=False) dhcp = forms.BooleanField( label=_("DHCP"), required=False, ) ipv4address = IP4AddressFormField( initial='', required=False, label=_("IPv4 Address"), ) ipv4netmaskbit = forms.ChoiceField( choices=choices.v4NetmaskBitList, required=False, label=_("IPv4 Netmask"), ) ipv4gw = IP4AddressFormField( initial='', required=False, label=_("IPv4 Default Gateway"), ) def __init__(self, *args, **kwargs): super(IPMIForm, self).__init__(*args, **kwargs) self.fields['dhcp'].widget.attrs['onChange'] = ( 'javascript:toggleGeneric(' '"id_dhcp", ["id_ipv4address", "id_ipv4netmaskbit"]);') def clean_ipmi_password2(self): ipmi_password1 = self.cleaned_data.get("ipmi_password1", "") ipmi_password2 = self.cleaned_data["ipmi_password2"] if ipmi_password1 != ipmi_password2: raise forms.ValidationError( _("The two password fields didn't match.")) return ipmi_password2 def clean_ipv4netmaskbit(self): try: cidr = int(self.cleaned_data.get("ipv4netmaskbit")) except ValueError: return None bits = 0xffffffff ^ (1 << 32 - cidr) - 1 return socket.inet_ntoa(pack('>I', bits))
def __init__(self, *args, **kwargs): super(VcenterConfigurationForm, self).__init__(*args, **kwargs) self.fields['vc_management_ip'] = forms.ChoiceField( choices=list(IPChoices()), label=_('TrueNAS Management IP Address')) self.is_https = True if 'https' in self.get_sys_protocol().lower( ) else False self.vcp_is_installed = self.instance.vc_installed self.is_update_needed()
class iSCSITargetGroupsForm(MiddlewareModelForm, ModelForm): middleware_attr_prefix = "iscsi_target_" middleware_plugin = "iscsi.target" is_singletone = False iscsi_target_authgroup = forms.ChoiceField(label=_("Authentication Group number")) class Meta: fields = '__all__' model = models.iSCSITargetGroups exclude = ('iscsi_target_initialdigest', ) def __init__(self, *args, **kwargs): super(iSCSITargetGroupsForm, self).__init__(*args, **kwargs) self.fields['iscsi_target_authgroup'].required = False self.fields['iscsi_target_authgroup'].choices = [(-1, _('None'))] + [(i['iscsi_target_auth_tag'], i['iscsi_target_auth_tag']) for i in models.iSCSITargetAuthCredential.objects.all().values('iscsi_target_auth_tag').distinct()] def clean_iscsi_target_authgroup(self): value = self.cleaned_data.get('iscsi_target_authgroup') return None if value and int(value) == -1 else value def middleware_clean(self, data): targetobj = self.cleaned_data.get('iscsi_target') with client as c: target = c.call('iscsi.target.query', [('id', '=', targetobj.id)], {'get': True}) data['auth'] = data.pop('authgroup') or None data['authmethod'] = AUTHMETHOD_LEGACY_MAP.get(data.pop('authtype')) data['initiator'] = data.pop('initiatorgroup') data['portal'] = data.pop('portalgroup') if self.instance.id: orig = models.iSCSITargetGroups.objects.get(pk=self.instance.id).__dict__ old = { 'authmethod': AUTHMETHOD_LEGACY_MAP.get(orig['iscsi_target_authtype']), 'portal': orig['iscsi_target_portalgroup_id'], 'initiator': orig['iscsi_target_initiatorgroup_id'], 'auth': orig['iscsi_target_authgroup'], } for idx, i in enumerate(target['groups']): if ( i['portal'] == old['portal'] and i['initiator'] == old['initiator'] and i['auth'] == old['auth'] and i['authmethod'] == old['authmethod'] ): break else: raise forms.ValidationError('Target group not found') target['groups'][idx] = data else: target['groups'].append(data) self.instance.id = targetobj.id target.pop('id') return target
class DiskWipeForm(forms.Form): method = forms.ChoiceField( label=_("Method"), choices=( ("quick", _("Quick")), ("full", _("Full with zeros")), ("fullrandom", _("Full with random data")), ), widget=forms.widgets.RadioSelect(), )
def __init__(self, *args, **kwargs): super(VcenterConfigurationForm, self).__init__(*args, **kwargs) sys_guiprotocol = self.get_sys_protocol() if sys_guiprotocol.upper() == "HTTPS": self.is_https = True else: self.is_https = False ip_choices = utils.get_management_ips() self.fields['vc_management_ip'] = forms.ChoiceField( choices=list(zip(ip_choices, ip_choices)), label=_('TrueNAS Management IP Address'), )
def __init__(self, *args, **kwargs): super(SettingsForm, self).__init__(*args, **kwargs) self.instance._original_stg_guiprotocol = self.instance.stg_guiprotocol self.instance._original_stg_guiaddress = self.instance.stg_guiaddress self.instance._original_stg_guiport = self.instance.stg_guiport self.instance._original_stg_syslogserver = self.instance.stg_syslogserver self.fields['stg_language'].choices = settings.LANGUAGES self.fields['stg_language'].label = _("Language (Require UI reload)") self.fields['stg_guiaddress'] = forms.ChoiceField( label=self.fields['stg_guiaddress'].label) self.fields['stg_guiaddress'].choices = [['0.0.0.0', '0.0.0.0'] ] + list(choices.IPChoices())
class iSCSITargetPortalForm(MiddlewareModelForm, ModelForm): middleware_attr_map = { 'discovery_authmethod': 'iscsi_target_portal_discoveryauthmethod', 'discovery_authgroup': 'iscsi_target_portal_discoveryauthgroup', } middleware_attr_prefix = 'iscsi_target_portal_' middleware_attr_schema = 'iscsiportal' middleware_plugin = 'iscsi.portal' is_singletone = False iscsi_target_portal_discoveryauthgroup = forms.ChoiceField( label=_("Discovery Auth Group")) class Meta: fields = '__all__' model = models.iSCSITargetPortal widgets = { 'iscsi_target_portal_tag': forms.widgets.HiddenInput(), } def __init__(self, *args, **kwargs): super(iSCSITargetPortalForm, self).__init__(*args, **kwargs) self._listen = [] self.fields['iscsi_target_portal_discoveryauthgroup'].required = False self.fields['iscsi_target_portal_discoveryauthgroup'].choices = [ (None, _('None')) ] + [(i['iscsi_target_auth_tag'], i['iscsi_target_auth_tag']) for i in models.iSCSITargetAuthCredential.objects.all().values( 'iscsi_target_auth_tag').distinct()] def cleanformset_iscsitargetportalip(self, fs, forms): for form in forms: if not hasattr(form, 'cleaned_data'): continue if form.cleaned_data.get('DELETE'): continue self._listen.append({ 'ip': form.cleaned_data.get('iscsi_target_portalip_ip'), 'port': form.cleaned_data.get('iscsi_target_portalip_port'), }) return True def middleware_clean(self, data): data['listen'] = self._listen data['discovery_authmethod'] = AUTHMETHOD_LEGACY_MAP.get( data.pop('discoveryauthmethod')) data['discovery_authgroup'] = data.pop('discoveryauthgroup') or None data.pop('tag', None) return data
class CharacterSetForm(forms.ModelForm): """ We use this form to create Character set objects, and update them. It creates the form from the CharacterSet model and adds the filter and range fields as a form of input. Filter takes in any input text and filters out (by default CJK) characters. Range takes in a range of the format e.g. "8,A..F,11" """ filter_text = forms.CharField( required=False, widget=forms.widgets.Textarea(), label="Enter any text and the text will be filtered") filter = forms.ChoiceField(required=False, label="A regex for filtering submission text", choices=FILTERS) range = forms.CharField( required=False, widget=forms.widgets.Textarea(), label= "Enter a range like: 8,10..15,17 is equivalent to 8,10,11,12,13,14,15,17" ) class Meta: model = CharacterSet exclude = ('id', 'user', 'characters') def __init__(self, *args, **kwargs): super(CharacterSetForm, self).__init__(*args, **kwargs) #self.fields['lang'].label = "Language" try: self.fields['lang'].label = "Language" except: pass def save(self, *args, **kwargs): m = super(CharacterSetForm, self).save(commit=False, *args, **kwargs) #print self.cleaned_data['range'], "___", self.cleaned_data['filter'] if self.cleaned_data['range'] != "": m.set = CharacterSet.get_set_from_range_string( self.cleaned_data['range']) #print "in range:", m.set m.save_string() elif self.cleaned_data['filter_text'] != "": f = self.cleaned_data['filter'] m.set = CharacterSet.get_set_with_filter( self.cleaned_data['filter_text'], f) #print "in filter:", m.set, f m.save_string() m.save() return m
def __init__(self, *args, **kwargs): super(UPSForm, self).__init__(*args, **kwargs) ports = filter(lambda x: x.find('.') == -1, glob.glob('/dev/cua*')) ports.extend(glob.glob('/dev/ugen*')) self.fields['ups_port'] = forms.ChoiceField(label=_("Port")) self.fields['ups_port'].widget = forms.widgets.ComboBox() self.fields['ups_port'].choices = [(port, port) for port in ports] if self.data and self.data.get("ups_port"): self.fields['ups_port'].choices.insert( 0, (self.data.get("ups_port"), self.data.get("ups_port"))) elif self.instance.id: self.fields['ups_port'].choices.insert( 0, (self.instance.ups_port, self.instance.ups_port))
def __init__(self, *args, **kwargs): super(VcenterConfigurationForm, self).__init__(*args, **kwargs) self.fields['vc_management_ip'] = forms.ChoiceField( choices=list(IPChoices()), label=_('TrueNAS Management IP Address') ) with client as c: self.is_https = c.call('system.general.config')['ui_httpsredirect'] self.vcp_is_installed = self.instance.vc_installed self.is_update_needed()
class LAGGInterfaceForm(forms.Form): lagg_protocol = forms.ChoiceField(choices=choices.LAGGType, widget=forms.RadioSelect()) lagg_interfaces = forms.MultipleChoiceField( widget=forms.SelectMultiple(), label=_('Physical NICs in the LAGG') ) def __init__(self, *args, **kwargs): super(LAGGInterfaceForm, self).__init__(*args, **kwargs) self.fields['lagg_interfaces'].choices = list( choices.NICChoices(nolagg=True) )
class IPMIIdentifyForm(Form): period = forms.ChoiceField( label=_("Identify Period"), choices=choices.IPMI_IDENTIFY_PERIOD, initial='15', ) def save(self): with client as c: period = self.cleaned_data.get('period') if period == 'force': data = {'force': True} else: data = {'seconds': period} return c.call('ipmi.identify', data)
def __init__(self, *args, **kwargs): repl = kwargs.get('instance', None) super(ReplicationForm, self).__init__(*args, **kwargs) self.fields['repl_filesystem'] = forms.ChoiceField( label=self.fields['repl_filesystem'].label, ) fs = list( set([(task.task_filesystem, task.task_filesystem) for task in models.Task.objects.all()])) self.fields['repl_filesystem'].choices = fs if repl and repl.id: self.fields['remote_hostname'].initial = ( repl.repl_remote.ssh_remote_hostname) self.fields['remote_port'].initial = ( repl.repl_remote.ssh_remote_port) self.fields['remote_hostkey'].initial = ( repl.repl_remote.ssh_remote_hostkey)
def __init__(self, *args, **kwargs): self.jail = None if kwargs and kwargs.has_key('jail'): self.jail = kwargs.pop('jail') super(NullMountPointForm, self).__init__(*args, **kwargs) if kwargs and kwargs.has_key('instance'): self.instance = kwargs.pop('instance') if self.jail: self.fields['jail'].initial = self.jail.jail_host self.fields['jail'].widget.attrs = { 'readonly': True, 'class': ( 'dijitDisabled dijitTextBoxDisabled' 'dijitValidationTextBoxDisabled' ), } self.jc = JailsConfiguration.objects.order_by("-id")[0] jail_path = "%s/%s" % (self.jc.jc_path, self.jail.jail_host) self.fields['destination'].widget.attrs['root'] = (jail_path) else: self.fields['jail'] = forms.ChoiceField( label=_("Jail"), choices=(), widget=forms.Select(attrs={'class': 'required'}), ) jc = JailsConfiguration.objects.order_by("-id")[0] try: clean_path_execbit(jc.jc_path) except forms.ValidationError, e: self.errors['__all__'] = self.error_class(e.messages) pjlist = [] wlist = Warden().list() for wj in wlist: if wj[WARDEN_KEY_STATUS] == WARDEN_STATUS_RUNNING: pjlist.append(wj[WARDEN_KEY_HOST]) self.fields['jail'].choices = [(pj, pj) for pj in pjlist ]