Esempio n. 1
0
 class ManageForm(forms.Form):
     name = forms.CharField(required=True)
     description = forms.CharField(required=False)
     if locks:
       lock_start = SatoriDateTimeField(required=False)
       lock_finish = SatoriDateTimeField(required=False)
       lock_address = forms.IPAddressField(required=False)
       lock_netmask = forms.IPAddressField(required=False)
     viewfield = viewing.field()
     joinfield = joining.field()
     questions = forms.BooleanField(label='Questions allowed',required=False)
     backups = forms.BooleanField(label='Backups allowed',required=False)            
     prints = forms.BooleanField(label='Prints allowed',required=False)            
Esempio n. 2
0
 class ManageForm(forms.Form):
     name = forms.CharField(required=True)
     description = forms.CharField(required=False)
     if locks:
       lock_start = SatoriDateTimeField(required=False)
       lock_finish = SatoriDateTimeField(required=False)
       lock_address = forms.IPAddressField(required=False)
       lock_netmask = forms.IPAddressField(required=False)
     viewfield = viewing.field()
     joinfield = joining.field()
     questions = forms.BooleanField(label='Questions allowed',required=False)
     backups = forms.BooleanField(label='Backups allowed',required=False)            
     prints = forms.BooleanField(label='Prints allowed',required=False)            
     printer = forms.ChoiceField(label='Printer', choices=[[-1,'None']]+[[p.id, p.name] for p in Printer.filter()], required=False)
Esempio n. 3
0
class ServerListSubmit(forms.Form):
    server_internal_ip = forms.IPAddressField(label="内网IP地址")
    server_external_ip = forms.IPAddressField(
        label="外网IP地址", error_messages={'required': u'外网ip地址不能为空'})
    server_os = forms.CharField(label="服务器操作系统",
                                error_messages={'required': u'操作系统不能为空'})
    server_admin = forms.CharField(label="服务器管理员",
                                   error_messages={'required': u'系统管理员不能为空'})
    server_password = forms.CharField(label="服务器管理密码",
                                      error_messages={'required': u'密码不能为空'})
    server_ssh_port = forms.IntegerField(
        label="服务器ssh端口", error_messages={'required': u'ssh端口不能为空'})
    server_hostname = forms.CharField(label="服务器主机名",
                                      error_messages={'required': u'主机名不能为空'})
    provider = forms.CharField(label="供应商")
Esempio n. 4
0
class RINORSetupForm(forms.Form):
    ip = forms.IPAddressField(max_length=15, label="Server IP address")
    port = forms.DecimalField(decimal_places=0,
                              min_value=0,
                              label="Server port")
    prefix = forms.CharField(max_length=50,
                             label="Url prefix (without '/')",
                             required=False)

    def clean(self):
        cleaned_data = self.cleaned_data
        ip = cleaned_data.get("ip")
        port = cleaned_data.get("port")
        prefix = cleaned_data.get("prefix")
        if ip and port:
            # Check RINOR Server access
            if prefix:
                url = "http://%s:%s/%s/" % (ip, port, prefix)
            else:
                url = "http://%s:%s/" % (ip, port)
            try:
                filehandle = urllib.urlopen(url)
            except IOError:
                raise forms.ValidationError(
                    "Can not connect the Domogik server, please check ip")

        # Always return the full collection of cleaned data.
        return cleaned_data
Esempio n. 5
0
class ReloadFcgiForm(forms.Form):
    method = forms.ChoiceField(choices=(('threaded', 'threaded'), ('prefork',
                                                                   'prefork')),
                               initial='threaded')
    pidfile = forms.CharField(min_length=4,
                              max_length=50,
                              initial='/tmp/fcgi.pid')
    host = forms.IPAddressField(initial='127.0.0.1')
    port = forms.IntegerField(min_value=1, max_value=10000, initial=8001)
    minspare = forms.IntegerField(min_value=1, max_value=9, initial=4)
    maxspare = forms.IntegerField(min_value=2, max_value=10, initial=5)
    socket = forms.CharField(min_length=4, max_length=50, required=False)
    protocol = forms.ChoiceField(choices=(('fcgi', 'fcgi'), ('scgi', 'scgi'),
                                          ('ajp', 'ajp')),
                                 initial='fcgi',
                                 required=False)
    maxrequests = forms.IntegerField(min_value=0,
                                     max_value=100000,
                                     required=False)
    maxchildren = forms.IntegerField(min_value=1, max_value=10, required=False)

    def reload_fcgi(self):
        options = ' '.join(
            ['%s=%s' % (k, v) for k, v in self.cleaned_data.iteritems() if v])
        manage_py = os.path.join(settings.BASE_DIR, 'manage.py')
        command_name = 'runfcgi'
        python_path = check_output('which python', shell=True).strip()
        cmd = ('kill `cat {pidfile}` && {python_path} {manage_py} '
               '{command_name} {options}').format(
                   pidfile=self.cleaned_data['pidfile'], **locals())
        check_output(cmd, shell=True)
Esempio n. 6
0
class GraphicsForm(forms.ModelForm):
    class Meta:
        model = virt.models.Device
        exclude = (
            'xml',
            'domain',
            'type',
        )

    graphics_type = forms.CharField(
        max_length=3, widget=forms.Select(choices=virt.models.GRAPHICTYPES))
    sdl_display = forms.CharField(label=_('SDL Display'),
                                  max_length=25,
                                  required=False)
    sdl_xauth = forms.CharField(label=_('SDL Xauth'),
                                max_length=25,
                                required=False)
    sdl_fullscreen = forms.BooleanField(label=_('SDL FullScreen ?'),
                                        required=False)
    autoport = forms.BooleanField(label=_('Auto Port'),
                                  required=False,
                                  initial=True)
    vnc_port = forms.IntegerField(label=_('VNC Port'), required=False)
    vnc_listen = forms.IPAddressField(label=_('VNC Listen'), initial='0.0.0.0')
    vnc_passwd = forms.CharField(label=_('VNC Password'), required=False)
Esempio n. 7
0
class ConnectionFilterForm(forms.Form):
    connection_type = forms.CharField(label='State',
                                      required=False,
                                      max_length=255)

    connection_type.widget = forms.Select(attrs={
        'class': 'span10',
    },
                                          choices=STATE)

    connection_transport = forms.CharField(label='Transport',
                                           required=False,
                                           max_length=255)

    connection_transport.widget = forms.Select(attrs={
        'class': 'span10',
    },
                                               choices=TRANSPORT)

    connection_protocol = forms.CharField(label='Protocol',
                                          required=False,
                                          max_length=255)

    connection_protocol.widget = forms.Select(attrs={
        'class': 'span10',
    },
                                              choices=PROTOCOL)

    local_port = forms.IntegerField(label='Local Port', required=False)

    remote_host = forms.IPAddressField(label='Attacker', required=False)

    remote_port = forms.IntegerField(label='Remote Port', required=False)
Esempio n. 8
0
class HvmModifyVirtualMachineForm(ModifyVirtualMachineForm):
    hvparam_fields = ('boot_order', 'cdrom_image_path', 'nic_type',
                      'disk_type', 'vnc_bind_address', 'acpi', 'use_localtime')
    required = ('disk_type', 'boot_order', 'nic_type')
    empty_field = EMPTY_CHOICE_FIELD
    disk_types = HVM_CHOICES['disk_type']
    nic_types = HVM_CHOICES['nic_type']
    boot_devices = HVM_CHOICES['boot_order']

    acpi = forms.BooleanField(label='ACPI', required=False)
    use_localtime = forms.BooleanField(label='Use Localtime', required=False)
    vnc_bind_address = forms.IPAddressField(label='VNC Bind Address',
                                            required=False)
    disk_type = forms.ChoiceField(label=_('Disk Type'), choices=disk_types)
    nic_type = forms.ChoiceField(label=_('NIC Type'), choices=nic_types)
    boot_order = forms.ChoiceField(label=_('Boot Device'),
                                   choices=boot_devices)

    class Meta(ModifyVirtualMachineForm.Meta):
        exclude = ModifyVirtualMachineForm.Meta.exclude + (
            'kernel_path', 'root_path', 'kernel_args', 'serial_console',
            'cdrom2_image_path')

    def __init__(self, vm, *args, **kwargs):
        super(HvmModifyVirtualMachineForm, self).__init__(vm, *args, **kwargs)
Esempio n. 9
0
class CompleteForm(forms.Form):
    CHOICES = (
        (1, 'Cats'),
        (2, 'Dogs'),
        (3, 'Ravens'),
    )

    firstname = forms.CharField(help_text='Sue your parents!', required=False)
    name = forms.CharField()
    yesno = forms.BooleanField(label='Agree?', required=False)

    email = forms.EmailField(help_text="We'd love to spam you forever!")
    url = forms.URLField(help_text='Ze internets!!!')

    number = forms.IntegerField()
    floated = forms.FloatField(label='Float number')

    path = forms.FileField(label='File')
    image = forms.ImageField()
    choices = forms.ChoiceField(
        choices=CHOICES, initial=3,
        help_text='We already selected the smartest for you.'
    )
    sure = forms.BooleanField(
        label='You sure?', required=True,
        help_text='Should you have the choice'
    )
    text = forms.CharField(required=False, widget=forms.Textarea(attrs={'cols': 60, 'rows': 10}))
    mchoices = forms.MultipleChoiceField(label='Multiple choices', choices=CHOICES)
    choices2 = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect)
    mchoices2 = forms.MultipleChoiceField(
        label='Multiple choices', choices=CHOICES,
        widget=forms.CheckboxSelectMultiple
    )
    maybe = forms.NullBooleanField(required=False)
    ip = forms.IPAddressField(label='IP Address')
    decimal = forms.DecimalField()
    repeat = RepeatField(
        label='Repeat', initial=(False, None, None, None),
        help_text='Complext widget', required=False
    )

    date = forms.DateField()
    time = forms.TimeField()

    datetime = forms.DateTimeField(label='Date and time')
    splitdatetime = forms.SplitDateTimeField(label='Date and Time')

    # Convenient way to have some field groups.
    # You don't need to do it and can use field names in your templates but in this
    # case it was easier to use such a trick :)
    field_groups = (
        ('firstname', 'name', 'yesno'),
        ('email', 'url'),
        ('number', 'floated'),
        ('path', 'image', 'choices', 'sure', 'text'),
        ('mchoices', 'choices2', 'mchoices2', 'maybe', 'ip', 'decimal','repeat'),
        ('date', 'time'),
        ('datetime', 'splitdatetime',)
    )
Esempio n. 10
0
class TestForm(forms.Form):
    a_charfield = forms.CharField(help_text='Any string')
    a_textarea = forms.CharField(widget=forms.Textarea,
                                 help_text='Any paragraph')
    url = forms.URLField()
    a_boolean = forms.BooleanField()
    select_option = forms.ChoiceField(choices=CHOICES)
    a_date = forms.DateField()
    a_datetime = forms.DateTimeField()
    a_decimal = forms.DecimalField()
    an_email = forms.EmailField()
    a_file = forms.FileField()
    #a_filepath = forms.FilePathField()
    a_float = forms.FloatField()
    an_image = forms.ImageField()
    an_integer = forms.IntegerField()
    an_ipaddress = forms.IPAddressField()
    #a_generic_ipaddress = forms.GenericIPAddressField()
    a_multiple_choice = forms.MultipleChoiceField(choices=CHOICES)
    a_typed_multiple_choice = forms.TypedMultipleChoiceField(choices=CHOICES)
    a_null_boolean = forms.NullBooleanField()  #not sure what this should be
    a_regex = forms.RegexField(
        regex=r'<([A-Z][A-Z0-9]*)\b[^>]*>(.*?)</\1>')  #matches tags
    a_slug = forms.SlugField()
    a_time = forms.TimeField()
Esempio n. 11
0
class NewNodeForm(forms.Form):
    node_name = forms.CharField(label="Uzak İstemci Adı", max_length=30)

    ip_address = forms.IPAddressField(label="IP Adresi")

    port = forms.DecimalField(label="Port", initial="5220")

    auth_key = forms.CharField(label="Kimlik Doğrulama Anahtarı")
Esempio n. 12
0
class IpAccessStatusForm(forms.Form):
    ip_address_add      =   forms.IPAddressField()
    access_status_add   =   forms.HiddenInput()

    def clean_access_status(self):
        if not self.cleaned_data['access_status'] in ACCESS_STATUS:
            raise forms.ValidationError("Invalid Access Status.")
        return ACCESS_STATUS_MAP[self.cleaned_data['access_status']]
Esempio n. 13
0
 def __init__(self, contactFormInstance, request, *args, **kwargs):
     super(ContactFormPlus, self).__init__(*args, **kwargs)
     if 'instance' not in kwargs:
         for extraField in contactFormInstance.extrafield_set.all():
             if extraField.fieldType == 'CharField':
                 self.fields[slugify(extraField.label)] = forms.CharField(label=extraField.label, 
                         initial=extraField.initial, 
                         required=extraField.required)
             elif extraField.fieldType == 'BooleanField':
                 self.fields[slugify(extraField.label)] = forms.BooleanField(label=extraField.label, 
                         initial=extraField.initial, 
                         required=extraField.required)
             elif extraField.fieldType == 'EmailField':
                 self.fields[slugify(extraField.label)] = forms.EmailField(label=extraField.label, 
                         initial=extraField.initial, 
                         required=extraField.required)
             elif extraField.fieldType == 'DecimalField':
                 self.fields[slugify(extraField.label)] = forms.DecimalField(label=extraField.label, 
                         initial=extraField.initial, 
                         required=extraField.required)
             elif extraField.fieldType == 'FloatField':
                 self.fields[slugify(extraField.label)] = forms.FloatField(label=extraField.label, 
                         initial=extraField.initial, 
                         required=extraField.required)
             elif extraField.fieldType == 'IntegerField':
                 self.fields[slugify(extraField.label)] = forms.IntegerField(label=extraField.label, 
                         initial=extraField.initial, 
                         required=extraField.required)
             elif extraField.fieldType == 'IPAddressField':
                 self.fields[slugify(extraField.label)] = forms.IPAddressField(label=extraField.label, 
                         initial=extraField.initial, 
                         required=extraField.required)
             elif extraField.fieldType == 'auto_Textarea':
                 self.fields[slugify(extraField.label)] = forms.CharField(label=extraField.label, 
                         initial=extraField.initial,
                         widget=forms.Textarea,   
                         required=extraField.required)
             elif extraField.fieldType == 'auto_hidden_input':
                 self.fields[slugify(extraField.label)] = forms.CharField(label=extraField.label, 
                         initial = extraField.initial,
                         widget=forms.HiddenInput, 
                         required=False)
             elif extraField.fieldType == 'auto_referral_page':
                 lInitial = "No referral available."
                 if request:
                     lInitial = request.META.get('HTTP_REFERER', 'No referral available.')
                 self.fields[slugify(extraField.label)] = forms.CharField(label=extraField.label, 
                         initial = lInitial, #NOTE: This overwrites extraField.initial! 
                         widget=forms.HiddenInput, 
                         required=False) 
             elif extraField.fieldType == 'auto_GET_parameter':
                 lInitial = "Key/value parameter not available."
                 if request:
                     lInitial = request.GET.get(slugify(extraField.label), 'n/a')
                 self.fields[slugify(extraField.label)] = forms.CharField(label=extraField.label, 
                         initial = lInitial, #NOTE: This overwrites extraField.initial! 
                         widget=forms.HiddenInput, 
                         required=False)
Esempio n. 14
0
class ManyFieldsForm(forms.Form):

    booleanfield = forms.BooleanField()
    charfield = forms.CharField(max_length=40, null=True)
    datetimefield = forms.DateTimeField(auto_now_add=True)
    datefield = forms.DateField(auto_now_add=True)
    decimalfield = forms.DecimalField(max_digits=5, decimal_places=2)
    emailfield = forms.EmailField()
    filefield = forms.FileField(name='test_file', upload_to='test')
    filepathfield = forms.FilePathField(path='/some/path')
    floatfield = forms.FloatField()
    genericipaddressfield = forms.GenericIPAddressField()
    imagefield = forms.ImageField(name='test_image', upload_to='test')
    ipaddressfield = forms.IPAddressField()
    intfield = forms.IntegerField(null=True)
    nullbooleanfield = forms.NullBooleanField()
    slugfield = forms.SlugField()
    timefield = forms.TimeField()
    urlfield = forms.URLField()

    def boolean_field_tests(self):
        print(self.booleanfield | True)
        print(self.nullbooleanfield | True)

    def string_field_tests(self):
        print(self.charfield.strip())
        print(self.charfield.upper())
        print(self.charfield.replace('x', 'y'))

        print(self.filepathfield.strip())
        print(self.filepathfield.upper())
        print(self.filepathfield.replace('x', 'y'))

        print(self.emailfield.strip())
        print(self.emailfield.upper())
        print(self.emailfield.replace('x', 'y'))

    def datetimefield_tests(self):
        now = datetime.now()
        print(now - self.datetimefield)
        print(self.datetimefield.ctime())

    def datefield_tests(self):
        now = date.today()
        print(now - self.datefield)
        print(self.datefield.isoformat())

    def decimalfield_tests(self):
        print(self.decimalfield.adjusted())

    def filefield_tests(self):
        print(self.filefield)
        print(self.imagefield)

    def numberfield_tests(self):
        print(self.intfield + 5)
Esempio n. 15
0
class DomainsForm(forms.ModelForm):
    domain = forms.SlugField(label='Dinámico', required=True)
    ip = forms.IPAddressField(label='Dirección IP', required=True)

    class Meta:
        model = Domains
        fields = ('domain', 'ip')

    def clean_domain(self):
        return clean_unique(self, 'domain')
Esempio n. 16
0
class FeedBack(forms.Form):
	u"""Клас форми для зворотнього зв'язку"""
	readonly_fields = ("date",'ip_addr')
	ip_addr = forms.IPAddressField(label = u'IP адреса')
	name = forms.CharField(label = u'Ім\'я')
	date = forms.DateField(label = u'Дата', initial=datetime.datetime.now())
	email = forms.EmailField(label = u'E-mail',)
	text = forms.CharField(widget=forms.Textarea(),label = u'Текст сообщения')
	def __init__(self, readonly_form=False, *args, **kwargs):
		super(FeedBack, self).__init__(*args, **kwargs)
		for field in self.readonly_fields:
			self.fields[field].widget.attrs['readonly'] = True
Esempio n. 17
0
 class AXFRForm(NOCForm):
     ns = forms.CharField(
         label=_("NS"),
         help_text=
         _("Name server IP address. NS must have zone transfer enabled for NOC host"
           ))
     zone = forms.CharField(label=_("Zone"),
                            help_text=_("DNS Zone name to transfer"))
     source_address = forms.IPAddressField(
         label=_("Source Address"),
         required=False,
         help_text=_("Source address to issue zone transfer"))
Esempio n. 18
0
class ConfigureLBaaSForm(forms.Form):
    worker = forms.ChoiceField(choices=(("test", "test"), ("test2", "test2")))
    netscaler = forms.IPAddressField(label="NetScaler IP Address",
                                     required=True)
    virtual_ips = forms.CharField(label='Virtual IP Range:', required=True)

    def add_workers_into_form(self, workers):
        node_fqdns = workers.keys()
        node_fqdns.sort()
        choices = [generate_choice_entry(node_fqdn, workers[node_fqdn]) \
                                                  for node_fqdn in node_fqdns]
        self.fields["worker"].choices = \
            [("", "Please select a server...")] + choices
Esempio n. 19
0
class NetForm(forms.Form):
	OPTIONS = (
                ("1", "Static"),
                ("2", "DHCP"),
               )
	bootmode = forms.ChoiceField(choices=OPTIONS)
	#ipaddress = forms.IPAddressField(max_length=15,required=True, validators=[validators.validate_ipv46_address])
	ipaddress = forms.IPAddressField()
	validate_mask = validators.RegexValidator(regex=r'^255\.255\.255\.[0-5]{1,3}',message='Invalid subnet mask', code='invalid')
	subnetmask = forms.CharField(max_length=15, required=True, validators=[validate_mask])
	gateway = forms.CharField(max_length=15,required=True, validators=[validators.validate_ipv4_address])
	hostname = forms.CharField(max_length=25,required=True)
		
Esempio n. 20
0
File: forms.py Progetto: m3ouf/test
class CreateOrChangeForm(forms.Form):
    userName = forms.CharField(max_length=128)
    serviceName = forms.CharField(max_length=128, required=False)
    transactionId = forms.CharField(max_length=128, required=False)
    isOptionPack = forms.BooleanField(required=False)
    wanIp = forms.IPAddressField(required=False)
    wanMask = forms.IPAddressField(required=False)
    lanIp = forms.IPAddressField(required=False)
    lanMask = forms.IPAddressField(required=False)
    zone = forms.CharField(required=False, max_length=64)
    isVrf = forms.BooleanField(required=False)
    vrfName = forms.CharField(max_length=128, required=False)
    wanPeIp = forms.CharField(max_length=128, required=False)

    def clean(self):
        cleaned_data = super(CreateOrChangeForm, self).clean()
        if self.errors:
            return cleaned_data
        if not self.cleaned_data['isOptionPack'] and not self.cleaned_data[
                "serviceName"]:
            self._errors["serviceName"] = self.error_class(
                ["arguments ['serviceName'] are required but not provided"])

        if self.cleaned_data.get('isOptionPack', False):
            required_params = set(
                ['wanIp', 'wanMask', 'lanIp', 'lanMask', 'zone', 'wanPeIp'])
            provided_params = set(
            )  # I hate myself for doing this without dict comprehension but you can blame python2.6 :(
            for param in required_params:
                if self.cleaned_data[param]:
                    provided_params.add(param)
            if bool(required_params - provided_params):
                error_msg = "param [{0}] are required but not provided".format(
                    ",".join(required_params - provided_params))
                self._errors["optionPackErrors"] = self.error_class(
                    [error_msg])

        return cleaned_data
Esempio n. 21
0
class HostForm(forms.ModelForm):
    ipaddr = forms.IPAddressField(label=u'IP地址',
                                  required=True,
                                  help_text=u'主机的IP地址')
    user = forms.CharField(max_length=128,
                           label=u'登录用户',
                           help_text=u'登录主机的用户名,默认为root')
    password = forms.CharField(max_length=128, label=u'登录密码')
    group = forms.ModelChoiceField(queryset=Group.objects.all(),
                                   label=u'选择相应的组')

    class Meta:
        model = Host
        fields = ['ipaddr', 'user', 'password', 'group']
Esempio n. 22
0
class AssetsInfoForm(forms.Form):

    cabinet = forms.CharField(
        required=True,
        label=u"机柜",
        error_messages={'required': u'请输入机柜号'},
    )

    number = forms.IntegerField(
        required=True,
        label=u"序号",
        error_messages={'required': u'请输入序号'},
    )

    ip = forms.IPAddressField(required=True,
                              label=u"IP",
                              error_messages={'required': u'请输入ip'})

    server_name = forms.CharField(
        required=True,
        label=u"机器名",
        error_messages={'required': u'请输入机器名'},
    )

    description = forms.CharField(
        required=True,
        label=u"描述",
        error_messages={'required': u'请输描述信息'},
    )

    hard = forms.CharField(required=True,
                           label=u"硬盘",
                           error_messages={'required': u'请输入硬盘信息p'})

    SN = forms.CharField(required=True,
                         label=u"SN号",
                         error_messages={'required': u'请输入SN号'})

    remark = forms.CharField(required=False,
                             label=u"备注",
                             error_messages={'required': u'请输入备注信息'})

    status = forms.CharField(required=True,
                             label=u"状态",
                             error_messages={'required': u'请输入状态信息'})

    raid = forms.CharField(required=True,
                           label=u"raid",
                           error_messages={'required': u'请输入raid信息'})
Esempio n. 23
0
class EditInterfaceForm(forms.Form):
    type = forms.TypedChoiceField(
        label=_("Type"),
        choices=(('dhcp', _('DHCP')), ('static', _('Static'))),
        widget=forms.RadioSelect,
        initial='dhcp',
        required=True,
    )
    ipaddress = forms.IPAddressField(_('IP address'), required=False)
    netmask = forms.IPAddressField(_('Netmask'), required=False)
    gateway = forms.IPAddressField(_('Gateway'), required=False)
    dns1 = forms.IPAddressField(_('First DNS server'), required=False)
    dns2 = forms.IPAddressField(_('Second DNS server'), required=False)

    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.helper.form_class = 'form-horizontal'
        self.helper.form_class = 'form-horizontal'
        self.helper.layout = Layout(
            Field('type', disabled=True), Field('ipaddress', disabled=True),
            Field('netmask', disabled=True), Field('gateway', disabled=True),
            Field('dns1', disabled=True), Field('dns2', disabled=True),
            FormActions(Submit('submit', 'Submit', css_class="btn-primary")))
        super(EditInterfaceForm, self).__init__(*args, **kwargs)

    def clean(self):
        cleaned_data = super(EditInterfaceForm, self).clean()
        t = cleaned_data.get("type")

        if t == 'static':
            for f in ['ipaddress', 'netmask', 'gateway', 'dns1', 'dns2']:
                if not cleaned_data.get(f):
                    self._errors[f] = self.error_class(
                        [_('This field is required.')])

        return cleaned_data
Esempio n. 24
0
class AllElementsForm(forms.Form):
    boolean_checkbox = forms.BooleanField()
    text_input = forms.CharField(help_text="Sample text input",
                                 max_length=50,
                                 min_length=10)
    textarea_input = forms.CharField(help_text="Sample textarea",
                                     max_length=50,
                                     min_length=10,
                                     widget=forms.Textarea)
    choices_field = forms.ChoiceField(choices=((('1', 'One'), ('2', 'Two'),
                                                ('3', 'Three'))))
    choices_radio_field = forms.ChoiceField(choices=((('1', 'One'), ('2',
                                                                     'Two'),
                                                      ('3', 'Three'))),
                                            widget=forms.RadioSelect)
    date_field = forms.DateField(input_formats=['%d.%m.%Y'],
                                 initial=datetime.now())
    datetime_field = forms.DateTimeField(input_formats=['%d.%m.%Y %H:%M'],
                                         initial=datetime.now())
    decimal_field = forms.DecimalField(max_value=100,
                                       min_value=10,
                                       max_digits=5,
                                       decimal_places=2)
    email_field = forms.EmailField(min_length=5, max_length=50)
    file_field = forms.FileField(max_length=250,
                                 help_text='Attach any file here')
    filepath_field = forms.FilePathField(path=os.path.join(
        settings.BASE_DIR, 'tests/templates'),
                                         recursive=True)
    float_field = forms.FloatField(min_value=10, max_value=100)
    image_field = forms.ImageField()
    integer_field = forms.IntegerField(min_value=10, max_value=100)
    ipaddress_field = forms.IPAddressField()
    generic_ipaddress_field = forms.GenericIPAddressField(protocol='IPv6')
    multiplechoice_field = forms.MultipleChoiceField(
        (('1', 'One'), ('2', 'Two'), ('3', 'Three'), ('4', 'Four'),
         ('5', 'Five'), ('6', 'Siz')))
    nullboolean_field = forms.NullBooleanField()
    regex_field = forms.RegexField(regex='[a-zA-Z]+')
    slug_field = forms.SlugField()
    time_field = forms.TimeField(input_formats=['%H:%M'],
                                 initial=datetime.now())
    url_field = forms.URLField(min_length=10, max_length=100)
    combo_field = forms.ComboField(
        fields=[forms.CharField(
            max_length=20), forms.EmailField()])
    splitdatetime_field = forms.SplitDateTimeField(
        input_date_formats=['%d.%m.%Y'], input_time_formats=['%H:%M'])
class FieldTypeForm(forms.Form):
    boolean_field = forms.BooleanField()
    char_field = forms.CharField()
    choice_field = forms.ChoiceField()
    date_field = forms.DateField()
    date_time_field = forms.DateTimeField()
    decimal_field = forms.DecimalField()
    email_field = forms.EmailField()
    file_field = forms.FileField()
    float_field = forms.FloatField()
    integer_field = forms.IntegerField()
    ip_address_field = forms.IPAddressField()
    multiple_choice_field = forms.MultipleChoiceField()
    null_boolean_field = forms.NullBooleanField()
    slug_field = forms.SlugField()
    time_field = forms.TimeField()
    url_field = forms.URLField()
Esempio n. 26
0
class JobConfigForm(forms.Form):
    """
    comment of class
    """
    hostname = forms.IPAddressField(
        error_messages={'required': 'Please enter the hostname'},
        required=True,
        max_length=30)
    db_type = forms.ChoiceField(
        error_messages={'required': 'Please enter the database type'},
        choices=DB_TYPES)
    db_name = forms.CharField(max_length=100, required=False)
    db_username = forms.CharField(max_length=100, required=False)
    db_password = forms.CharField(max_length=100,
                                  widget=forms.PasswordInput,
                                  required=False)
    run_every = forms.IntegerField(
        error_messages={'required': 'Please enter the run every period'},
        required=True,
        widget=forms.Select(choices=RUN_EVERY))
Esempio n. 27
0
class PayuPaymentForm(forms.Form):
    buyer_first_name = forms.CharField(widget=TextInput(
        attrs={"placeholder": ""}))
    buyer_last_name = forms.CharField(widget=TextInput(
        attrs={"placeholder": ""}))
    buyer_email = forms.EmailField(widget=TextInput(attrs={"placeholder": ""}))
    buyer_ip_address = forms.IPAddressField(widget=HiddenInput())

    product_name = forms.CharField(widget=TextInput(attrs={"placeholder": ""}))
    product_unit_price = forms.IntegerField(widget=NumberInput(
        attrs={"placeholder": ""}))
    product_quantity = forms.IntegerField(widget=NumberInput(
        attrs={"placeholder": ""}))

    purchase_description = forms.CharField(widget=Textarea(
        attrs={
            "rows": 3,
            "placeholder": "Describe your payment"
        }))

    continue_url = forms.URLField()
Esempio n. 28
0
 class MyForm(forms.ModelForm):
     ipaddress = forms.IPAddressField()
Esempio n. 29
0
class NetworkConfigForm(forms.Form):
    modes = ((
        "dhcp",
        "DHCP",
    ), ("static", "Static"))
    mode = forms.ChoiceField(widget=forms.widgets.RadioSelect, choices=modes)
    address = forms.IPAddressField(label="IP Address", required=False)
    subnet = forms.IPAddressField(required=False, label="Subnet")
    gateway = forms.IPAddressField(required=False)
    nameservers = forms.CharField(required=False, max_length=256)
    proxy_address = forms.CharField(required=False, max_length=256)
    proxy_port = forms.CharField(required=False)
    proxy_username = forms.CharField(required=False)
    proxy_password = forms.CharField(required=False)

    def get_network_settings(self):
        """Usage: ./TSquery [options]
             --all, -a           Output all information (default)
             --proxy_info        Output just proxy http info
             --eth_info          Output just ethernet info
             --eth-dev           Specify eth device to query (default = eth0)
             --json              Output json format
             --outputfile, -o    Write output to file
        Outputs:
        http_proxy:not set
        network_device:eth0
        network_mode:dhcp
        network_address:10.0.2.15
        network_subnet:255.255.255.0
        network_gateway:10.0.2.2
        """
        settings = {
            "mode": "",
            "address": "",
            "subnet": "",
            "gateway": "",
            "nameservers": "",
            "proxy_address": "",
            "proxy_port": "",
            "proxy_username": "",
            "proxy_password": "",
        }
        cmd = ["/usr/sbin/TSquery"]
        try:
            proc = subprocess.Popen(cmd,
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)
            stdout, stderr = proc.communicate()
            out_lines = stdout.split("\n")
            formatted_output = "\n".join("    %s" % l for l in out_lines)
            logger.info("TSquery output:\n%s" % formatted_output)
            for line in out_lines:
                if line:
                    key, value = line.split(":", 1)
                    if key.startswith("network_"):
                        key = key.replace("network_", '', 1)
                    settings[key] = value
        except Exception as error:
            logger.error("When attempting to run TSquery:\n%s" % error)
        return settings

    def new_config(self, one, two, keys):
        return not all(k in one and k in two and one[k] == two[k]
                       for k in keys)

    def set_to_current_values(self):
        settings = self.get_network_settings()
        self.fields['mode'].initial = settings["mode"]
        self.fields['address'].initial = settings["address"]
        self.fields['subnet'].initial = settings["subnet"]
        self.fields['gateway'].initial = settings["gateway"]
        self.fields['nameservers'].initial = settings["nameservers"]
        self.fields['proxy_address'].initial = settings["proxy_address"]
        self.fields['proxy_port'].initial = settings["proxy_port"]
        self.fields['proxy_username'].initial = settings["proxy_username"]
        self.fields['proxy_password'].initial = settings["proxy_password"]

    def __init__(self, *args, **kw):
        super(NetworkConfigForm, self).__init__(*args, **kw)
        self.set_to_current_values()

    def save(self, *args, **kw):
        host_task, proxy_task, dns_task = None, None, None
        settings = self.get_network_settings()
        host_config = ["mode", "address", "subnet", "gateway"]
        if self.new_config(self.cleaned_data, settings, host_config):
            logger.info("User changed the host network settings.")
            if self.cleaned_data['mode'] == "dhcp":
                host_task = tasks.dhcp.delay()
            elif self.cleaned_data['mode'] == "static":
                address = self.cleaned_data['address']
                subnet = self.cleaned_data['subnet']
                gateway = self.cleaned_data['gateway']
                host_task = tasks.static_ip.delay(address, subnet, gateway)
        proxy_config = [
            "proxy_address", "proxy_port", "proxy_username", "proxy_password"
        ]
        if self.new_config(self.cleaned_data, settings, proxy_config):
            logger.info("User changed the proxy settings.")
            if self.cleaned_data['proxy_address'] and self.cleaned_data[
                    'proxy_port']:
                address = self.cleaned_data['proxy_address']
                port = self.cleaned_data['proxy_port']
                user = self.cleaned_data['proxy_username']
                password = self.cleaned_data['proxy_password']
                proxy_task = tasks.proxyconf.delay(address, port, user,
                                                   password)
            else:
                proxy_task = tasks.ax_proxy.delay()
        if self.new_config(self.cleaned_data, settings, ["nameservers"]):
            logger.info("User changed the DNS settings.")
            if self.cleaned_data['nameservers']:
                dns_task = tasks.dnsconf.delay(
                    self.cleaned_data['nameservers'])
        if host_task:
            host_task.get()
        if proxy_task:
            proxy_task.get()
        if dns_task:
            dns_task.get()
        self.set_to_current_values()
Esempio n. 30
0
class NetworkConfigForm(forms.Form):
    modes = ((
        "dhcp",
        "DHCP",
    ), ("static", "Static"))
    mode = forms.ChoiceField(widget=forms.widgets.RadioSelect, choices=modes)
    address = forms.IPAddressField(label="IP Address", required=False)
    subnet = forms.IPAddressField(required=False, label="Subnet")
    gateway = forms.IPAddressField(required=False)
    nameservers = forms.CharField(required=False, max_length=256)
    dnssearch = forms.CharField(required=False,
                                max_length=256,
                                label="Search Domain")
    proxy_address = forms.CharField(required=False, max_length=256)
    proxy_port = forms.CharField(required=False)
    proxy_username = forms.CharField(required=False)
    proxy_password = forms.CharField(required=False)
    no_proxy = forms.CharField(required=False,
                               max_length=256,
                               label="Set no_proxy")
    default_no_proxy = settings.DEFAULT_NO_PROXY

    def get_network_settings(self):
        """Usage: /usr/sbin/TSquery [option]...
        --eth-dev                 Specify eth device to query
        --debug, -d               Prints script commands when executing (set -x)
        --help, -h                Prints command line args
        --version, -v             Prints version

        Outputs:
            proxy_address:
            proxy_port:
            proxy_username:
            proxy_password:
            no_proxy:
            network_device:
            network_mode:
            network_address:10.25.3.211
            network_subnet:255.255.254.0
            network_gateway:10.25.3.1
            network_nameservers:10.25.3.2,10.45.16.11
            network_dnssearch:ite,itw,cbd
        """
        settings = {
            "mode": "",
            "address": "",
            "subnet": "",
            "gateway": "",
            "nameservers": "",
            "dnssearch": "",
            "proxy_address": "",
            "proxy_port": "",
            "proxy_username": "",
            "proxy_password": "",
            "no_proxy": "",
        }
        cmd = ["/usr/sbin/TSquery"]
        try:
            proc = subprocess.Popen(cmd,
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)
            stdout, stderr = proc.communicate()
            out_lines = stdout.split("\n")
            formatted_output = "\n".join("    %s" % l for l in out_lines)
            logger.info("TSquery output:\n%s" % formatted_output)
            for line in out_lines:
                if line:
                    key, value = line.split(":", 1)
                    if key.startswith("network_"):
                        key = key.replace("network_", '', 1)
                    settings[key] = value
        except Exception as error:
            logger.error("When attempting to run TSquery:\n%s" % error)
        return settings

    def new_config(self, one, two, keys):
        return not all(k in one and k in two and one[k] == two[k]
                       for k in keys)

    def set_to_current_values(self):
        settings = self.get_network_settings()
        self.fields['mode'].initial = settings["mode"]
        self.fields['address'].initial = settings["address"]
        self.fields['subnet'].initial = settings["subnet"]
        self.fields['gateway'].initial = settings["gateway"]
        self.fields['nameservers'].initial = settings["nameservers"]
        self.fields['dnssearch'].initial = settings["dnssearch"]
        self.fields['proxy_address'].initial = settings["proxy_address"]
        self.fields['proxy_port'].initial = settings["proxy_port"]
        self.fields['proxy_username'].initial = settings["proxy_username"]
        self.fields['proxy_password'].initial = settings["proxy_password"]
        self.fields['no_proxy'].initial = settings["no_proxy"]

    def __init__(self, *args, **kw):
        super(NetworkConfigForm, self).__init__(*args, **kw)
        self.set_to_current_values()

    def save(self, *args, **kw):
        def ax_proxy():
            """
            Helper method for TSsetproxy script which will automatically set the "--remove" argument
            """
            cmd = ["sudo", "/usr/sbin/TSsetproxy", "--remove"]
            proc = subprocess.Popen(cmd,
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)
            stdout, stderr = proc.communicate()
            if stderr:
                logger.warning("Network error: %s" % stderr)

        def proxyconf(address, port, username, password):
            """
            Helper method for TSsetproxy script
            :param address:  --address     Proxy address (http://proxy.net)
            :param port:     --port        Proxy port number
            :param username: --username    Username for authentication
            :param password: --password    Password for authentication
            """
            cmd = [
                "sudo", "/usr/sbin/TSsetproxy", "--address", address, "--port",
                port, "--username", username, "--password", password
            ]
            proc = subprocess.Popen(cmd,
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)
            stdout, stderr = proc.communicate()
            if stderr:
                logger.warning("Network error: %s" % stderr)

        def dhcp():
            """
            Helper method to call into the TSstaticip script with the "remove" option to revert back to dhcp
            """
            cmd = ["sudo", "/usr/sbin/TSstaticip", "--remove"]
            proc = subprocess.Popen(cmd,
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)
            stdout, stderr = proc.communicate()
            if stderr:
                logger.warning("Network error: %s" % stderr)

        def static_ip(address, subnet, gateway, nameserver=None, search=None):
            """
            Helper method to call into the TSstaticip script
            :param address:    --ip         Define host IP address
            :param subnet:     --nm         Define subnet mask (netmask)
            :param gateway:    --gw         Define gateway/router IP address
            :param nameserver: --nameserver Specify one or more nameserver IP addresses
            :param search:     --search     Specify one or more search domains
            """
            cmd = [
                "sudo", "/usr/sbin/TSstaticip", "--ip", address, "--nm",
                subnet, "--gw", gateway
            ]
            if nameserver:
                cmd += ["--nameserver", nameserver]
            if search:
                cmd += ["--search", search]
            proc = subprocess.Popen(cmd,
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)
            stdout, stderr = proc.communicate()
            if stderr:
                logger.warning("Network error: %s" % stderr)

        network_settings = self.get_network_settings()
        host_config = ["mode", "address", "subnet", "gateway"]
        if self.new_config(self.cleaned_data, network_settings, host_config):
            if self.cleaned_data['mode'] == "dhcp":
                dhcp()
            elif self.cleaned_data['mode'] == "static":
                address = self.cleaned_data['address']
                subnet = self.cleaned_data['subnet']
                gateway = self.cleaned_data['gateway']
                nameservers = None
                dnssearch = None

                if self.new_config(self.cleaned_data, network_settings,
                                   ["nameservers", "dnssearch"]):
                    logger.info(
                        "User changed the DNS and host network settings.")
                    if self.cleaned_data['nameservers']:
                        nameservers = self.cleaned_data['nameservers']

                    if self.cleaned_data['dnssearch']:
                        dnssearch = self.cleaned_data['dnssearch']

                logger.info("User changed the host network settings.")
                static_ip(address,
                          subnet,
                          gateway,
                          nameserver=nameservers,
                          search=dnssearch)
        else:
            logger.info("new_config failed to pass")

        proxy_config = [
            "proxy_address", "proxy_port", "proxy_username", "proxy_password"
        ]
        if self.new_config(self.cleaned_data, network_settings, proxy_config):
            logger.info("User changed the proxy settings.")
            if self.cleaned_data['proxy_address'] and self.cleaned_data[
                    'proxy_port']:
                address = self.cleaned_data['proxy_address']
                port = self.cleaned_data['proxy_port']
                user = self.cleaned_data['proxy_username']
                password = self.cleaned_data['proxy_password']
                proxyconf(address, port, user, password)
            else:
                ax_proxy()

        self.set_to_current_values()