class OrganizerSettingsForm(SettingsForm): organizer_info_text = I18nFormField( label=_('Info text'), required=False, widget=I18nTextarea, help_text=_('Not displayed anywhere by default, but if you want to, you can use this e.g. in ticket templates.') ) event_team_provisioning = forms.BooleanField( label=_('Allow creating a new team during event creation'), help_text=_('Users that do not have access to all events under this organizer, must select one of their teams ' 'to have access to the created event. This setting allows users to create an event-specified team' ' on-the-fly, even when they do not have \"Can change teams and permissions\" permission.'), required=False, ) primary_color = forms.CharField( label=_("Primary color"), required=False, validators=[ RegexValidator(regex='^#[0-9a-fA-F]{6}$', message=_('Please enter the hexadecimal code of a color, e.g. #990000.')), ], widget=forms.TextInput(attrs={'class': 'colorpickerfield'}) ) theme_color_success = forms.CharField( label=_("Accent color for success"), help_text=_("We strongly suggest to use a shade of green."), required=False, validators=[ RegexValidator(regex='^#[0-9a-fA-F]{6}$', message=_('Please enter the hexadecimal code of a color, e.g. #990000.')), ], widget=forms.TextInput(attrs={'class': 'colorpickerfield'}) ) theme_color_danger = forms.CharField( label=_("Accent color for errors"), help_text=_("We strongly suggest to use a shade of red."), required=False, validators=[ RegexValidator(regex='^#[0-9a-fA-F]{6}$', message=_('Please enter the hexadecimal code of a color, e.g. #990000.')), ], widget=forms.TextInput(attrs={'class': 'colorpickerfield'}) ) theme_color_background = forms.CharField( label=_("Page background color"), required=False, validators=[ RegexValidator(regex='^#[0-9a-fA-F]{6}$', message=_('Please enter the hexadecimal code of a color, e.g. #990000.')), ], widget=forms.TextInput(attrs={'class': 'colorpickerfield no-contrast'}) ) theme_round_borders = forms.BooleanField( label=_("Use round edges"), required=False, ) organizer_homepage_text = I18nFormField( label=_('Homepage text'), required=False, widget=I18nTextarea, help_text=_('This will be displayed on the organizer homepage.') ) organizer_logo_image = ExtFileField( label=_('Header image'), ext_whitelist=(".png", ".jpg", ".gif", ".jpeg"), max_size=10 * 1024 * 1024, required=False, help_text=_('If you provide a logo image, we will by default not show your organization name ' 'in the page header. By default, we show your logo with a size of up to 1140x120 pixels. You ' 'can increase the size with the setting below. We recommend not using small details on the picture ' 'as it will be resized on smaller screens.') ) organizer_logo_image_large = forms.BooleanField( label=_('Use header image in its full size'), help_text=_('We recommend to upload a picture at least 1170 pixels wide.'), required=False, ) event_list_type = forms.ChoiceField( label=_('Default overview style'), choices=( ('list', _('List')), ('week', _('Week calendar')), ('calendar', _('Month calendar')), ) ) event_list_availability = forms.BooleanField( label=_('Show availability in event overviews'), help_text=_('If checked, the list of events will show if events are sold out. This might ' 'make for longer page loading times if you have lots of events and the shown status might be out ' 'of date for up to two minutes.'), required=False ) organizer_link_back = forms.BooleanField( label=_('Link back to organizer overview on all event pages'), required=False ) locales = forms.MultipleChoiceField( choices=settings.LANGUAGES, label=_("Use languages"), widget=MultipleLanguagesWidget, help_text=_('Choose all languages that your organizer homepage should be available in.') ) primary_font = forms.ChoiceField( label=_('Font'), choices=[ ('Open Sans', 'Open Sans') ], widget=FontSelect, help_text=_('Only respected by modern browsers.') ) favicon = ExtFileField( label=_('Favicon'), ext_whitelist=(".ico", ".png", ".jpg", ".gif", ".jpeg"), required=False, max_size=1 * 1024 * 1024, help_text=_('If you provide a favicon, we will show it instead of the default pretix icon. ' 'We recommend a size of at least 200x200px to accommodate most devices.') ) giftcard_length = forms.IntegerField( label=_('Length of gift card codes'), help_text=_('The system generates by default {}-character long gift card codes. However, if a different length ' 'is required, it can be set here.'.format(settings.ENTROPY['giftcard_secret'])), required=False ) giftcard_expiry_years = forms.IntegerField( label=_('Validity of gift card codes in years'), help_text=_('If you set a number here, gift cards will by default expire at the end of the year after this ' 'many years. If you keep it empty, gift cards do not have an explicit expiry date.'), required=False ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['primary_font'].choices += [ (a, {"title": a, "data": v}) for a, v in get_fonts().items() ]
class LoginForm(AuthenticationForm): username = forms.CharField(label="Username", max_length=30, widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'username'})) password = forms.CharField(label="Password", max_length=30, widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'password'}))
class BackupFilterForm(forms.Form): """ Filter backups on backup node. """ dc = forms.ChoiceField( label=_('Datacenter'), required=False, widget=forms.Select( attrs={'class': 'fill-up input-navigation select-transparent'})) hostname = forms.ChoiceField( label=_('Server'), required=False, widget=forms.Select( attrs={'class': 'fill-up input-navigation select-transparent'})) type = forms.ChoiceField( label=_('Backup type'), required=False, choices=(('', _('Type (all)')), ) + Backup.TYPE, widget=forms.Select( attrs={'class': 'fill-up input-navigation select-transparent'})) status = forms.ChoiceField( label=_('Status'), required=False, choices=(('', _('Status (all)')), ) + Backup.STATUS, widget=forms.Select( attrs={'class': 'fill-up input-navigation select-transparent'})) min_size = forms.IntegerField( label=_('Larger than'), required=False, widget=forms.TextInput( attrs={ 'class': 'fill-up input-navigation input-transparent', 'placeholder': _('Larger than (MB)') })) max_size = forms.IntegerField( label=_('Smaller than'), required=False, widget=forms.TextInput( attrs={ 'class': 'fill-up input-navigation input-transparent', 'placeholder': _('Smaller than (MB)') })) created_since = forms.DateField( label=_('Created since'), required=False, input_formats=('%Y-%m-%d', ), widget=forms.DateInput( format='%Y-%m-%d', attrs={ 'placeholder': _('Created since'), 'class': 'fill-up input-navigation input-transparent ' 'input-date' })) created_until = forms.DateField( label=_('Created until'), required=False, input_formats=('%Y-%m-%d', ), widget=forms.DateInput( format='%Y-%m-%d', attrs={ 'placeholder': _('Created until'), 'class': 'fill-up input-navigation input-transparent ' 'input-date' })) def __init__(self, request, node, data, **kwargs): super(BackupFilterForm, self).__init__(data, **kwargs) vms = list( node.backup_set.values('vm__hostname', 'vm__alias').annotate( bkps=Count('id')).order_by('vm__hostname')) vms_list = [('', _('Server (all)'))] if vms and not vms[-1]['vm__hostname']: # We have backups without VM no_vm = vms.pop() vms_list.append(('novm', _('(no server) (%s)') % no_vm['bkps'])) self.qs = {} self.vm = None self.no_vm = False self.all_vm = True self.fields['dc'].choices = [('', _('Datacenter (all)'))] + list( get_dcs(request).values_list('name', 'alias')) self.fields['hostname'].choices = vms_list + [ (vm['vm__hostname'], '%s (%s)' % (vm['vm__hostname'], vm['bkps'])) for vm in vms ] def get_filters(self): data = self.cleaned_data query = [] hostname = data.get('hostname') if hostname: self.all_vm = False if hostname == 'novm': self.no_vm = True query.append(Q(vm__isnull=True)) else: try: self.vm = Vm.objects.select_related('dc').get( hostname=hostname) except Vm.DoesNotExist: raise Http404 else: query.append(Q(vm__hostname=hostname)) dc = data.get('dc') if dc: query.append(Q(dc__name=dc)) _type = data.get('type') if _type: query.append(Q(type=_type)) status = data.get('status') if status: query.append(Q(status=status)) min_size = data.get('min_size') if min_size: query.append(Q(size__gte=t_long(min_size) * 1048576)) max_size = data.get('max_size') if max_size: query.append(Q(size__lte=t_long(max_size) * 1048576)) created_since = data.get('created_since') if created_since: query.append(Q(created__gte=created_since)) created_until = data.get('created_until') if created_until: query.append(Q(created__lte=created_until)) if query: return reduce(and_, query) else: return None
class InstallationForm(forms.Form): url = forms.CharField( label="Installation Url", help_text=_('The "base URL" for your GitHub enterprise instance, ' 'includes the host and protocol.'), widget=forms.TextInput( attrs={'placeholder': _('https://github.example.com')} ), ) id = forms.CharField( label="GitHub App ID", help_text=_('The App ID of your Sentry app. This can be ' 'found on your apps configuration page.'), widget=forms.TextInput( attrs={'placeholder': _('1')} ) ) name = forms.CharField( label="GitHub App Name", help_text=_('The GitHub App name of your Sentry app. ' 'This can be found on the apps configuration ' 'page.'), widget=forms.TextInput( attrs={'placeholder': _('our-sentry-app')} ) ) verify_ssl = forms.BooleanField( label=_("Verify SSL"), help_text=_('By default, we verify SSL certificates ' 'when delivering payloads to your GitHub ' 'Enterprise instance'), widget=forms.CheckboxInput(), required=False ) webhook_secret = forms.CharField( label="GitHub App Webhook Secret", help_text=_('We require a webhook secret to be ' 'configured. This can be generated as any ' 'random string value of your choice and ' 'should match your GitHub app ' 'configuration.'), widget=forms.TextInput( attrs={'placeholder': _('XXXXXXXXXXXXXXXXXXXXXXXXXXX')} ) ) private_key = forms.CharField( label="GitHub App Private Key", help_text=_('The Private Key generated for your Sentry ' 'GitHub App.'), widget=forms.Textarea( attrs={'rows': '60', 'placeholder': _("-----BEGIN RSA PRIVATE KEY-----\n" "XXXXXXXXXXXXXXXXXXXXXXXXXXX\n" "XXXXXXXXXXXXXXXXXXXXXXXXXXX\n" "XXXXXXXXXXXXXXXXXXXXXXXXXXX\n" "XXXXXXXXXXXXXXXXXXXXXXXXXXX\n" "-----END RSA PRIVATE KEY-----"), } ) ) client_id = forms.CharField( label="GitHub App OAuth Client ID", widget=forms.TextInput( attrs={'placeholder': _('1')} ) ) client_secret = forms.CharField( label="GitHub App OAuth Client Secret", widget=forms.TextInput( attrs={'placeholder': _('XXXXXXXXXXXXXXXXXXXXXXXXXXX')} ) ) def __init__(self, *args, **kwargs): super(InstallationForm, self).__init__(*args, **kwargs) self.fields['verify_ssl'].initial = True
class ScheduleForm(forms.ModelForm): class Meta: model = Schedule fields = [ 'policy', 'on_mon', 'on_tue', 'on_wed', 'on_thu', 'on_fri', 'on_sat', 'on_sun', 'from_hours', 'from_mins', 'to_hours','to_mins' ] from_hours = forms.CharField(max_length=2, widget=forms.TextInput(attrs={'size':'5','class':'span2'})) from_mins = forms.CharField(max_length=2, widget=forms.TextInput(attrs={'size':'5','class':'span2'})) to_hours = forms.CharField(max_length=2, widget=forms.TextInput(attrs={'size':'5','class':'span2'})) to_mins = forms.CharField(max_length=2, widget=forms.TextInput(attrs={'size':'5','class':'span2'})) def clean(self): form_data = self.cleaned_data # see if at least one week day is checked checked = False for field in ['on_mon', 'on_tue', 'on_wed', 'on_thu', 'on_fri', 'on_sat', 'on_sun']: value = form_data[field] if value: checked = True break if not checked: raise forms.ValidationError("Please, select at least one day of week.") # the to hours must be at least more than from from_hours = form_data['from_hours'] to_hours = form_data['to_hours'] if int(from_hours) > int(to_hours): raise forms.ValidationError("'From Hour' must be at least less than or equal to 'To Hour'.") if int(from_hours) == int(to_hours): from_mins = form_data['from_mins'] to_mins = form_data['to_mins'] if int(from_mins) >= int(to_mins): raise forms.ValidationError("'From Minutes' must be at least less than 'To Minutes'.") return form_data def clean_from_hours(self): value = 0 try: value = int(self.cleaned_data['from_hours']) if value < 0 or value > 23: raise forms.ValidationError("Hours must be within interval from 00 to 23.") except TypeError: raise forms.ValidationError("Hours must be within interval from 00 to 23.") except ValueError: raise forms.ValidationError("Hours must be within interval from 00 to 23.") return value def clean_from_mins(self): value = 0 try: value = int(self.cleaned_data['from_mins']) if value < 0 or value > 59: raise forms.ValidationError("Minutes must be within interval from 00 to 59.") except TypeError: raise forms.ValidationError("Minutes must be within interval from 00 to 59.") except ValueError: raise forms.ValidationError("Minutes must be within interval from 00 to 59.") return value def clean_to_hours(self): value = 0 try: value = int(self.cleaned_data['to_hours']) if value < 0 or value > 23: raise forms.ValidationError("Hours must be within interval from 00 to 23.") except TypeError: raise forms.ValidationError("Hours must be within interval from 00 to 23.") except ValueError: raise forms.ValidationError("Hours must be within interval from 00 to 23.") return value def clean_to_mins(self): value = 0 try: value = int(self.cleaned_data['to_mins']) if value < 0 or value > 59: raise forms.ValidationError("Minutes must be within interval from 00 to 59.") except TypeError: raise forms.ValidationError("Minutes must be within interval from 00 to 59.") except ValueError: raise forms.ValidationError("Minutes must be within interval from 00 to 59.") return value
class in_mat(forms.Form): Matricula = forms.CharField(max_length=45, required=True, widget=forms.TextInput (attrs={"value":""}))
class AuthenticationForm(forms.Form): """ Base class for authenticating users. Extend this to get a form that accepts username/password logins. """ username = UsernameField(widget=forms.TextInput(attrs={'autofocus': True})) password = forms.CharField( label=_("Password"), strip=False, widget=forms.PasswordInput(attrs={'autocomplete': 'current-password'}), ) error_messages = { 'invalid_login': _( "Please enter a correct %(username)s and password. Note that both " "fields may be case-sensitive." ), 'inactive': _("This account is inactive."), } def __init__(self, request=None, *args, **kwargs): """ The 'request' parameter is set for custom auth use by subclasses. The form data comes in via the standard 'data' kwarg. """ self.request = request self.user_cache = None super().__init__(*args, **kwargs) # Set the max length and label for the "username" field. self.username_field = UserModel._meta.get_field(UserModel.USERNAME_FIELD) username_max_length = self.username_field.max_length or 254 self.fields['username'].max_length = username_max_length self.fields['username'].widget.attrs['maxlength'] = username_max_length if self.fields['username'].label is None: self.fields['username'].label = capfirst(self.username_field.verbose_name) def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username is not None and password: self.user_cache = authenticate(self.request, username=username, password=password) if self.user_cache is None: raise self.get_invalid_login_error() else: self.confirm_login_allowed(self.user_cache) return self.cleaned_data def confirm_login_allowed(self, user): """ Controls whether the given User may log in. This is a policy setting, independent of end-user authentication. This default behavior is to allow login by active users, and reject login by inactive users. If the given user cannot log in, this method should raise a ``forms.ValidationError``. If the given user may log in, this method should return None. """ if not user.is_active: raise forms.ValidationError( self.error_messages['inactive'], code='inactive', ) def get_user(self): return self.user_cache def get_invalid_login_error(self): return forms.ValidationError( self.error_messages['invalid_login'], code='invalid_login', params={'username': self.username_field.verbose_name}, )
class ContactForm(forms.Form): name = forms.CharField(label="", max_length=30, widget= forms.TextInput(attrs={'placeholder':'Nom', 'class': "form-control"})) email = forms.EmailField(label="", widget=forms.EmailInput(attrs={'placeholder':'Email', 'class': "form-control"})) content = forms.CharField(label="", widget=forms.Textarea(attrs={'placeholder':'Ecrivez votre message ici ...', 'class': "form-control", }))
class TiankongProblemAddForm(forms.Form): title = forms.CharField(label='标题', widget=forms.TextInput( attrs={'class': 'form-control', 'data-validation': 'required', 'data-validation-error-msg': "请输入题目标题"})) description = forms.CharField(label='题目描述', widget=forms.Textarea( attrs={'class': 'form-control', 'rows': '3', 'data-validation': 'required', 'data-validation-error-msg': "请输入题目描述"})) input = forms.CharField(label='输入描述', widget=forms.Textarea(attrs={'class': 'form-control', 'rows': '3'}), required=False) output = forms.CharField(label='输出描述', widget=forms.Textarea(attrs={'class': 'form-control', 'rows': '3'}), required=False) sample_code = forms.CharField(label='未完善的程序代码', widget=forms.Textarea( attrs={'class': 'form-control', 'rows': '20', "spellcheck": "false", "placeholder": "示例:\n#include<stdio.h>\nint fun(int,int);\nint main(){\n int a,b;\n scanf(\"%d,%d\",a,b); \n sum=a+b;\n return 0;\n}\n//请在下面填写你的答案\nint fun(int,int)"}), required=False) sample_input1 = forms.CharField(label='样例输入1', widget=forms.Textarea(attrs={'class': 'form-control', 'rows': '3'}), required=False) sample_output1 = forms.CharField(label='样例输出1', widget=forms.Textarea(attrs={'class': 'form-control', 'rows': '3'}), required=False) sample_input2 = forms.CharField(label='样例输入2', widget=forms.Textarea(attrs={'class': 'form-control', 'rows': '3'}), required=False) sample_output2 = forms.CharField(label='样例输出2', widget=forms.Textarea(attrs={'class': 'form-control', 'rows': '3'}), required=False) time_limit = forms.IntegerField(label='时间限制', widget=forms.TextInput( attrs={'class': 'form-control', 'type': 'number', 'aria-describedby': 'basic-addon2'}), initial=1) memory_limit = forms.IntegerField(label='内存限制', widget=forms.TextInput( attrs={'class': 'form-control', 'type': 'number', 'aria-describedby': 'basic-addon2'}), initial=128) classname = forms.ModelChoiceField(label='所属课程', queryset=ClassName.objects.all(), widget=forms.Select(attrs={'class': 'form-control'}), required=False) keypoint = forms.CharField(label='知识点,请从下面的下拉菜单中选择添加', widget=forms.TextInput( attrs={'type': 'hidden', 'data-validation': 'required', 'data-validation-error-msg': "请输入题目标题"})) def save(self, user, problemid=None): cd = self.cleaned_data title = cd['title'] description = cd['description'] input = cd['input'] output = cd['output'] sample_code = cd['sample_code'] sample_input1 = cd['sample_input1'] sample_output1 = cd['sample_output1'] sample_input2 = cd['sample_input2'] sample_output2 = cd['sample_output2'] time_limit = cd['time_limit'] memory_limit = cd['memory_limit'] keypoint = cd['keypoint'].split(',') if problemid: problem = Problem.objects.get(pk=problemid) problem.title = title problem.description = description problem.time_limit = time_limit problem.memory_limit = memory_limit problem.input = input problem.output = output problem.sample_input = sample_input1 problem.sample_output = sample_output1 problem.sample_input2 = sample_input2 problem.sample_output2 = sample_output2 #problem.creater = user problem.knowledgePoint1.clear() problem.knowledgePoint2.clear() problem.sample_code = sample_code else: problem = Problem( title=title, description=description, time_limit=time_limit, memory_limit=memory_limit, input=input, output=output, sample_input=sample_input1, sample_output=sample_output1, sample_input2=sample_input2, sample_output2=sample_output2, creater=user, problem_type="填空", sample_code = sample_code ) problem.save() for point in keypoint: problem.knowledgePoint2.add(KnowledgePoint2.objects.get(pk=point)) for point in problem.knowledgePoint2.all(): problem.knowledgePoint1.add(point.upperPoint) for point in problem.knowledgePoint1.all(): problem.classname.add(point.classname) problem.save() return problem
class CarreraForm(forms.ModelForm): nombre=forms.CharField(widget=forms.TextInput(attrs={"class":"form-control"})) class Meta: model=Carrera fields='__all__'
class LoginForm(forms.Form): username = forms.CharField(widget=forms.TextInput( attrs={'placeholder': 'Email'})) password = forms.CharField(widget=forms.PasswordInput( attrs={'placeholder': 'Hasło'}))
class EditProfileForm(UserChangeForm): password = forms.CharField(label="", widget=forms.TextInput(attrs={'type':'hidden'})) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password',)
class VirtualMachineForm(forms.Form): def __init__(self, *args, **kwargs): virtualization_api = kwargs.pop('virtualization_api', None) super(VirtualMachineForm, self).__init__(*args, **kwargs) self.fields['system'].choices = [ (system.pk, system.name) for system in System.objects.filter( virtual=True, pk=System.Type.KVM_VM ) ] architectures, image_list = virtualization_api.get_image_list() self.fields['architecture'].choices = [(architectures[0], architectures[0])] self.fields['image'].choices = [('none', 'None')] + image_list def clean(self): """Set `image` to None; cast `decimal.Decimal()` to `int`.""" cleaned_data = super(VirtualMachineForm, self).clean() if cleaned_data['image'] == 'none': cleaned_data['image'] = None cleaned_data['networkinterfaces'] = int(cleaned_data['networkinterfaces']) cleaned_data['ram_amount'] = int(cleaned_data['ram_amount']) cleaned_data['disk_size'] = int(cleaned_data['disk_size']) return cleaned_data uefi_boot = forms.BooleanField( label='Use UEFI boot', required=False, initial=False ) ram_amount = forms.DecimalField( label='Memory (MB)', required=True, initial=2048, max_value=16384, min_value=512, help_text='Value between 512MB and 16384MB.', widget=forms.NumberInput(attrs={'class': 'form-control'}) ) image = forms.ChoiceField( required=True, choices=[], widget=forms.Select(attrs={'class': 'custom-select form-control'}) ) networkinterfaces = forms.DecimalField( required=True, initial=1, max_value=5, min_value=1, widget=forms.NumberInput(attrs={'class': 'form-control'}) ) parameters = forms.CharField( required=False, help_text="e.g. '--cdrom /dev/cdrom'", widget=forms.TextInput(attrs={'class': 'form-control'}) ) system = forms.ChoiceField( required=True, choices=[], widget=forms.Select(attrs={'class': 'custom-select form-control'}), initial=0 ) architecture = forms.ChoiceField( required=True, choices=[], widget=forms.Select(attrs={'class': 'custom-select form-control'}), initial=0 ) disk_size = forms.DecimalField( label='Disk size (GB)', required=True, initial=10, max_value=50, min_value=10, help_text='Value between 10GB and 50GB; applies only if no image is selected.', widget=forms.NumberInput(attrs={'class': 'form-control'}) ) vnc = forms.BooleanField( label='Enable VNC', required=False, initial=True )
class SearchForm(forms.Form): def clean(self): cleaned_data = super(SearchForm, self).clean() empty = True values = [value for key, value in cleaned_data.items() if not key.endswith('__operator')] for value in values: if value: empty = False if empty: self.add_error(None, "Please provide at least one search parameter.") if cleaned_data['ram_amount']: try: int(cleaned_data['ram_amount']) except ValueError: self.add_error('ram_amount', "Value must be a number.") if cleaned_data['cpu_cores']: try: int(cleaned_data['cpu_cores']) except ValueError: self.add_error('cpu_cores', "Value must be a number.") def get_vendors(): vendors = [('', '--all--')] for vendor in Vendor.objects.all().values('id', 'name'): vendors.append((vendor['id'], vendor['name'])) return vendors def get_platforms(): platforms = [('', '--all--')] groups = {} for platform in Platform.objects.all(): id = platform.id name = platform.name vendor = platform.vendor if platform.is_cartridge: continue if vendor.name in groups.keys(): groups[vendor.name] += ((id, name),) else: groups[vendor.name] = ((id, name),) for vendor, platforms_ in groups.items(): platforms.append((vendor, platforms_)) return platforms def get_cartridge_platforms(): platforms = [('', '--all--')] groups = {} for platform in Platform.objects.all(): id = platform.id name = platform.name vendor = platform.vendor if not platform.is_cartridge: continue if vendor.name in groups.keys(): groups[vendor.name] += ((id, name),) else: groups[vendor.name] = ((id, name),) for vendor, platforms_ in groups.items(): platforms.append((vendor, platforms_)) return platforms def get_distributions(): installations = [('', '--all--')] for installation in Installation.objects.all().values('distribution').distinct(): installations.append((installation['distribution'], installation['distribution'])) return installations def get_systems(): """Return system choices.""" return Machine._meta.get_field('system').get_choices(blank_choice=[('', '--all--')]) def get_architectures(): """Return architecture choices.""" return Machine._meta.get_field('architecture').get_choices(blank_choice=[('', '--all--')]) enclosure__platform__vendor = forms.ChoiceField( required=False, choices=(get_vendors), widget=forms.Select(attrs={'class': 'custom-select form-control'}), ) enclosure__platform = forms.ChoiceField( required=False, choices=(get_platforms), widget=forms.Select(attrs={'class': 'custom-select form-control'}), ) platform = forms.ChoiceField( required=False, choices=(get_cartridge_platforms), widget=forms.Select(attrs={'class': 'custom-select form-control'}), ) system = forms.ChoiceField( required=False, choices=(get_systems), widget=forms.Select(attrs={'class': 'custom-select form-control'}), ) architecture = forms.ChoiceField( required=False, choices=(get_architectures), widget=forms.Select(attrs={'class': 'custom-select form-control'}), ) fqdn = forms.CharField( required=False, widget=forms.TextInput(attrs={'class': 'form-control'}) ) fqdn__operator = forms.CharField( initial='__icontains', widget=forms.HiddenInput() ) cpu_model = forms.CharField( required=False, widget=forms.TextInput(attrs={'class': 'form-control'}) ) cpu_model__operator = forms.CharField( initial='__icontains', widget=forms.HiddenInput() ) cpu_flags = forms.CharField( required=False, widget=forms.TextInput(attrs={'class': 'form-control'}) ) cpu_flags__operator = forms.CharField( initial='__icontains', widget=forms.HiddenInput() ) ram_amount = forms.DecimalField( required=False, min_value=1, widget=forms.NumberInput(attrs={'class': 'form-control'}) ) ram_amount__operator = forms.ChoiceField( choices=( ('__gt', '>'), ('__exact', '='), ('__lt', '<') ), required=False, initial='__gt', widget=forms.RadioSelect(attrs={'autocomplete': 'off'}) ) cpu_cores = forms.DecimalField( required=False, min_value=1, widget=forms.NumberInput(attrs={'class': 'form-control'}) ) cpu_cores__operator = forms.ChoiceField( choices=( ('__gt', '>'), ('__exact', '='), ('__lt', '<') ), required=False, initial='__gt', widget=forms.RadioSelect(attrs={'autocomplete': 'off'}) ) hwinfo = forms.CharField( required=False, widget=forms.TextInput(attrs={'class': 'form-control'}) ) hwinfo__operator = forms.CharField( initial='__icontains', widget=forms.HiddenInput() ) dmidecode = forms.CharField( required=False, widget=forms.TextInput(attrs={'class': 'form-control'}) ) dmidecode__operator = forms.CharField( initial='__icontains', widget=forms.HiddenInput() ) dmesg = forms.CharField( required=False, widget=forms.TextInput(attrs={'class': 'form-control'}) ) dmesg__operator = forms.CharField( initial='__icontains', widget=forms.HiddenInput() ) lspci = forms.CharField( required=False, widget=forms.TextInput(attrs={'class': 'form-control'}) ) lspci__operator = forms.CharField( initial='__icontains', widget=forms.HiddenInput() ) lsmod = forms.CharField( required=False, widget=forms.TextInput(attrs={'class': 'form-control'}) ) lsmod__operator = forms.CharField( initial='__icontains', widget=forms.HiddenInput() ) installations__distribution = forms.ChoiceField( required=False, choices=(get_distributions), widget=forms.Select(attrs={'class': 'custom-select form-control'}), ) reserved_by = forms.ChoiceField( required=False, choices=( ('__False', 'yes'), ('__True', 'no'), ('', 'not relevant') ), widget=forms.RadioSelect(attrs={'autocomplete': 'off'}) ) reserved_by__operator = forms.CharField( initial='__isnull', widget=forms.HiddenInput() ) ipmi = forms.ChoiceField( required=False, choices=( ('__True', 'yes'), ('__False', 'no'), ('', 'not relevant') ), widget=forms.RadioSelect(attrs={'autocomplete': 'off'}) ) efi = forms.ChoiceField( required=False, choices=( ('__True', 'yes'), ('__False', 'no'), ('', 'not relevant') ), widget=forms.RadioSelect(attrs={'autocomplete': 'off'}) ) networkinterfaces__mac_address = forms.CharField( required=False, widget=forms.TextInput(attrs={'class': 'form-control'}) ) networkinterfaces__mac_address__operator = forms.CharField( initial='__icontains', widget=forms.HiddenInput() ) serialconsole = forms.ChoiceField( required=False, choices=( ('__False', 'yes'), ('__True', 'no'), ('', 'not relevant') ), widget=forms.RadioSelect(attrs={'autocomplete': 'off'}) ) serialconsole__operator = forms.CharField( initial='__isnull', widget=forms.HiddenInput() ) remotepower = forms.ChoiceField( required=False, choices=( ('__False', 'yes'), ('__True', 'no'), ('', 'not relevant') ), widget=forms.RadioSelect(attrs={'autocomplete': 'off'}) ) remotepower__operator = forms.CharField( initial='__isnull', widget=forms.HiddenInput() ) status_ipv4 = forms.ChoiceField( required=False, choices=Machine._meta.get_field('status_ipv4').get_choices( blank_choice=[('', 'Not relevant')] ), widget=forms.Select(attrs={'class': 'custom-select form-control'}), ) status_ipv6 = forms.ChoiceField( required=False, choices=Machine._meta.get_field('status_ipv6').get_choices( blank_choice=[('', 'Not relevant')] ), widget=forms.Select(attrs={'class': 'custom-select form-control'}), ) status_ssh = forms.ChoiceField( required=False, choices=( ('__True', 'yes'), ('__False', 'no'), ('', 'not relevant') ), widget=forms.RadioSelect(attrs={'autocomplete': 'off'}) ) status_login = forms.ChoiceField( required=False, choices=( ('__True', 'yes'), ('__False', 'no'), ('', 'not relevant') ), widget=forms.RadioSelect(attrs={'autocomplete': 'off'}) ) status_abuild = forms.ChoiceField( required=False, choices=( ('__True', 'yes'), ('__False', 'no'), ('', 'not relevant') ), widget=forms.RadioSelect(attrs={'autocomplete': 'off'}) )
class RouteCreateForm(forms.Form): buildID = forms.ModelChoiceField(queryset=Building.objects.filter(buildExist=True)) destination = forms.CharField(max_length=100, widget=forms.TextInput (attrs={'placeholder':'ex. ERDT'})) roomNo = forms.IntegerField() directions = forms.CharField(widget=forms.Textarea)
class ProblemAddForm(forms.Form): title = forms.CharField(label='标题', widget=forms.TextInput( attrs={'class': 'form-control', 'data-validation': 'required', 'data-validation-error-msg': "请输入题目标题"})) description = forms.CharField(label='题目描述', widget=forms.Textarea( attrs={'class': 'form-control', 'rows': '3', 'data-validation': 'required', 'data-validation-error-msg': "请输入题目描述"})) input = forms.CharField(label='输入描述', widget=forms.Textarea(attrs={'class': 'form-control', 'rows': '3'}), required=False) output = forms.CharField(label='输出描述', widget=forms.Textarea(attrs={'class': 'form-control', 'rows': '3'}), required=False) program = forms.CharField(label='参考答案', widget=forms.Textarea(attrs={'class': 'form-control', 'rows': '20', "spellcheck": "false", 'data-validation': 'required','data-validation-error-msg': "请输入参考答案"})) sample_input1 = forms.CharField(label='样例输入1', widget=forms.Textarea(attrs={'class': 'form-control', 'rows': '3'}), required=False) sample_output1 = forms.CharField(label='样例输出1', widget=forms.Textarea(attrs={'class': 'form-control', 'rows': '3'}), required=False) sample_input2 = forms.CharField(label='样例输入2', widget=forms.Textarea(attrs={'class': 'form-control', 'rows': '3'}), required=False) sample_output2 = forms.CharField(label='样例输出2', widget=forms.Textarea(attrs={'class': 'form-control', 'rows': '3'}), required=False) time_limit = forms.IntegerField(label='时间限制', widget=forms.TextInput( attrs={'class': 'form-control', 'type': 'number', 'aria-describedby': 'basic-addon2'}), initial=1) memory_limit = forms.IntegerField(label='内存限制', widget=forms.TextInput( attrs={'class': 'form-control', 'type': 'number', 'aria-describedby': 'basic-addon2'}), initial=128) classname = forms.ModelChoiceField(label='所属课程', queryset=ClassName.objects.all(), widget=forms.Select(attrs={'class': 'form-control'}), required=False) keypoint = forms.CharField(label='知识点,请从下面的下拉菜单中选择添加', widget=forms.TextInput( attrs={'type': 'hidden', 'data-validation': 'required', 'data-validation-error-msg': "请输入题目标题"})) def save(self, user, problemid=None): cd = self.cleaned_data title = cd['title'] description = cd['description'] input = cd['input'] output = cd['output'] program = cd['program'] sample_input1 = cd['sample_input1'] sample_output1 = cd['sample_output1'] sample_input2 = cd['sample_input2'] sample_output2 = cd['sample_output2'] time_limit = cd['time_limit'] memory_limit = cd['memory_limit'] keypoint = cd['keypoint'].split(',') if problemid: problem = Problem.objects.get(pk=problemid) problem.title = title problem.description = description problem.time_limit = time_limit problem.memory_limit = memory_limit problem.input = input problem.output = output problem.sample_input = sample_input1 problem.sample_output = sample_output1 problem.sample_input2 = sample_input2 problem.sample_output2 = sample_output2 #problem.creater = user problem.knowledgePoint1.clear() problem.knowledgePoint2.clear() problem.program = program else: problem = Problem( title=title, description=description, time_limit=time_limit, memory_limit=memory_limit, input=input, output=output, sample_input=sample_input1, sample_output=sample_output1, sample_input2=sample_input2, sample_output2=sample_output2, creater=user, problem_type="编程", program=program ) problem.save() for point in keypoint: problem.knowledgePoint2.add(KnowledgePoint2.objects.get(pk=point)) for point in problem.knowledgePoint2.all(): problem.knowledgePoint1.add(point.upperPoint) for point in problem.knowledgePoint1.all(): problem.classname.add(point.classname) problem.save() return problem
class SentimentForm(forms.Form): review=forms.CharField(max_length=15000, widget=forms.TextInput(attrs={'placeholder': "Enter Review"}))
class RegistrationForm(forms.Form): """ Form for registering a new user account. Validates that the requested email is not already in use, and requires the password to be entered twice to catch typos. """ attrs_dict = {'class': 'input'} email = forms.CharField( widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=75)), label=_("Email address")) userid = forms.RegexField( regex=r'^\w+$', max_length=40, required=False, widget=forms.TextInput(), label=_("Username"), error_messages={'invalid': _("This value must be of length 40")}) password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), label=_("Password")) password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), label=_("Password (again)")) @classmethod def allow_register(self, email): prog = re.compile( r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", re.IGNORECASE) return False if prog.match(email) is None else True def clean_email(self): if user_number_over_limit(): raise forms.ValidationError( _("The number of users exceeds the limit.")) email = self.cleaned_data['email'] if not self.allow_register(email): raise forms.ValidationError(_("Enter a valid email address.")) emailuser = ccnet_threaded_rpc.get_emailuser(email) if not emailuser: return self.cleaned_data['email'] else: raise forms.ValidationError(_("User %s already exists.") % email) def clean_userid(self): if self.cleaned_data['userid'] and len( self.cleaned_data['userid']) != 40: raise forms.ValidationError(_("Invalid user id.")) return self.cleaned_data['userid'] def clean_password1(self): if 'password1' in self.cleaned_data: pwd = self.cleaned_data['password1'] if bool(config.USER_STRONG_PASSWORD_REQUIRED) is True: if bool(is_user_password_strong(pwd)) is True: return pwd else: raise forms.ValidationError( _(("%(pwd_len)s characters or more, include " "%(num_types)s types or more of these: " "letters(case sensitive), numbers, and symbols")) % { 'pwd_len': config.USER_PASSWORD_MIN_LENGTH, 'num_types': config.USER_PASSWORD_STRENGTH_LEVEL }) else: return pwd def clean_password2(self): """ Verifiy that the values entered into the two password fields match. Note that an error here will end up in ``non_field_errors()`` because it doesn't apply to a single field. """ if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data: if self.cleaned_data['password1'] != self.cleaned_data['password2']: raise forms.ValidationError( _("The two password fields didn't match.")) return self.cleaned_data
class LocationSearchForm(SearchForm): q = forms.CharField( required=False, label=('Search'), widget=forms.TextInput(attrs={'placeholder': 'Your address'}))
class ThemeForm(ThemeFormBase): name = forms.CharField(max_length=50) slug = forms.CharField(max_length=30) category = forms.ModelChoiceField(queryset=Category.objects.all(), widget=forms.widgets.RadioSelect) description = forms.CharField(widget=forms.Textarea(attrs={'rows': 4}), max_length=500, required=False) tags = forms.CharField(required=False) license = forms.TypedChoiceField( choices=amo.PERSONA_LICENSES_CHOICES, coerce=int, empty_value=None, widget=forms.HiddenInput, error_messages={'required': _(u'A license must be selected.')}) header = forms.FileField(required=False) header_hash = forms.CharField(widget=forms.HiddenInput) footer = forms.FileField(required=False) footer_hash = forms.CharField(widget=forms.HiddenInput, required=False) # Native color picker doesn't allow real time tracking of user input # and empty values, thus force the JavaScript color picker for now. # See bugs 1005206 and 1003575. accentcolor = ColorField( required=False, widget=forms.TextInput(attrs={'class': 'color-picker'}), ) textcolor = ColorField( required=False, widget=forms.TextInput(attrs={'class': 'color-picker'}), ) agreed = forms.BooleanField() # This lets us POST the data URIs of the unsaved previews so we can still # show them if there were form errors. It's really clever. unsaved_data = forms.CharField(required=False, widget=forms.HiddenInput) class Meta: model = Addon fields = ('name', 'slug', 'description', 'tags') def save(self, commit=False): data = self.cleaned_data addon = Addon.objects.create( slug=data.get('slug'), status=amo.STATUS_PENDING, type=amo.ADDON_PERSONA) addon.name = {'en-US': data['name']} if data.get('description'): addon.description = data['description'] addon._current_version = Version.objects.create(addon=addon, version='0') addon.save() # Create Persona instance. p = Persona() p.persona_id = 0 p.addon = addon p.header = 'header.png' if data['footer_hash']: p.footer = 'footer.png' if data['accentcolor']: p.accentcolor = data['accentcolor'].lstrip('#') if data['textcolor']: p.textcolor = data['textcolor'].lstrip('#') p.license = data['license'] p.submit = datetime.now() user = self.request.user p.author = user.username p.display_username = user.name p.save() # Save header, footer, and preview images. save_theme.delay(data['header_hash'], data['footer_hash'], addon) # Save user info. addon.addonuser_set.create(user=user, role=amo.AUTHOR_ROLE_OWNER) # Save tags. for t in data['tags']: Tag(tag_text=t).save_tag(addon) # Save categories. AddonCategory(addon=addon, category=data['category']).save() return addon
class PasswordResetForm(forms.Form): email = forms.EmailField( label=_("Email"), max_length=254, widget=forms.TextInput(attrs={'autocomplete': 'email'}) ) def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None): """ Send a django.core.mail.EmailMultiAlternatives to `to_email`. """ subject = loader.render_to_string(subject_template_name, context) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) body = loader.render_to_string(email_template_name, context) email_message = EmailMultiAlternatives(subject, body, from_email, [to_email]) if html_email_template_name is not None: html_email = loader.render_to_string(html_email_template_name, context) email_message.attach_alternative(html_email, 'text/html') email_message.send() def get_users(self, email): """Given an email, return matching user(s) who should receive a reset. This allows subclasses to more easily customize the default policies that prevent inactive users and users with unusable passwords from resetting their password. """ email_field_name = UserModel.get_email_field_name() active_users = UserModel._default_manager.filter(**{ '%s__iexact' % email_field_name: email, 'is_active': True, }) return ( u for u in active_users if u.has_usable_password() and _unicode_ci_compare(email, getattr(u, email_field_name)) ) def save(self, domain_override=None, subject_template_name='registration/password_reset_subject.txt', email_template_name='registration/password_reset_email.html', use_https=False, token_generator=default_token_generator, from_email=None, request=None, html_email_template_name=None, extra_email_context=None): """ Generate a one-use only link for resetting password and send it to the user. """ email = self.cleaned_data["email"] email_field_name = UserModel.get_email_field_name() for user in self.get_users(email): if not domain_override: current_site = get_current_site(request) site_name = current_site.name domain = current_site.domain else: site_name = domain = domain_override user_email = getattr(user, email_field_name) context = { 'email': user_email, 'domain': domain, 'site_name': site_name, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'user': user, 'token': token_generator.make_token(user), 'protocol': 'https' if use_https else 'http', **(extra_email_context or {}), } self.send_mail( subject_template_name, email_template_name, context, from_email, user_email, html_email_template_name=html_email_template_name, )
class EditThemeForm(AddonFormBase): name = TransField(max_length=50, label=_('Give Your Theme a Name.')) slug = forms.CharField(max_length=30) category = forms.ModelChoiceField(queryset=Category.objects.all(), widget=forms.widgets.RadioSelect) description = TransField( widget=TransTextarea(attrs={'rows': 4}), max_length=500, required=False, label=_('Describe your Theme.')) tags = forms.CharField(required=False) accentcolor = ColorField( required=False, widget=forms.TextInput(attrs={'class': 'color-picker'}), ) textcolor = ColorField( required=False, widget=forms.TextInput(attrs={'class': 'color-picker'}), ) license = forms.TypedChoiceField( choices=amo.PERSONA_LICENSES_CHOICES, coerce=int, empty_value=None, widget=forms.HiddenInput, error_messages={'required': _(u'A license must be selected.')}) # Theme re-upload. header = forms.FileField(required=False) header_hash = forms.CharField(widget=forms.HiddenInput, required=False) footer = forms.FileField(required=False) footer_hash = forms.CharField(widget=forms.HiddenInput, required=False) class Meta: model = Addon fields = ('name', 'slug', 'description', 'tags') def __init__(self, *args, **kw): self.request = kw.pop('request') super(AddonFormBase, self).__init__(*args, **kw) addon = Addon.objects.no_cache().get(id=self.instance.id) persona = addon.persona # Allow theme artists to localize Name and Description. for trans in Translation.objects.filter(id=self.initial['name']): self.initial['name_' + trans.locale.lower()] = trans for trans in Translation.objects.filter( id=self.initial['description']): self.initial['description_' + trans.locale.lower()] = trans self.old_tags = self.get_tags(addon) self.initial['tags'] = ', '.join(self.old_tags) if persona.accentcolor: self.initial['accentcolor'] = '#' + persona.accentcolor if persona.textcolor: self.initial['textcolor'] = '#' + persona.textcolor self.initial['license'] = persona.license cats = sorted(Category.objects.filter(type=amo.ADDON_PERSONA, weight__gte=0), key=lambda x: x.name) self.fields['category'].choices = [(c.id, c.name) for c in cats] try: self.initial['category'] = addon.categories.values_list( 'id', flat=True)[0] except IndexError: pass for field in ('header', 'footer'): self.fields[field].widget.attrs = { 'data-upload-url': reverse('devhub.personas.reupload_persona', args=[addon.slug, 'persona_%s' % field]), 'data-allowed-types': 'image/jpeg|image/png' } def clean_slug(self): return clean_addon_slug(self.cleaned_data['slug'], self.instance) def save(self): addon = self.instance persona = addon.persona data = self.cleaned_data # Update Persona-specific data. persona_data = { 'license': int(data['license']), 'accentcolor': data['accentcolor'].lstrip('#'), 'textcolor': data['textcolor'].lstrip('#'), 'author': self.request.user.username, 'display_username': self.request.user.name } changed = False for k, v in persona_data.iteritems(): if v != getattr(persona, k): changed = True setattr(persona, k, v) if changed: persona.save() if self.changed_data: ActivityLog.create(amo.LOG.EDIT_PROPERTIES, addon) self.instance.modified = datetime.now() # Update Addon-specific data. changed = ( set(self.old_tags) != data['tags'] or # Check if tags changed. self.initial['slug'] != data['slug'] or # Check if slug changed. transfield_changed('description', self.initial, data) or transfield_changed('name', self.initial, data)) if changed: # Only save if addon data changed. super(EditThemeForm, self).save() # Update tags. tags_new = data['tags'] tags_old = [slugify(t, spaces=True) for t in self.old_tags] # Add new tags. for t in set(tags_new) - set(tags_old): Tag(tag_text=t).save_tag(addon) # Remove old tags. for t in set(tags_old) - set(tags_new): Tag(tag_text=t).remove_tag(addon) # Update category. if data['category'].id != self.initial['category']: addon_cat = addon.addoncategory_set.all()[0] addon_cat.category = data['category'] addon_cat.save() # Theme reupload. if not addon.is_pending(): if data['header_hash'] or data['footer_hash']: save_theme_reupload.delay( data['header_hash'], data['footer_hash'], addon) return data
def contribute_to_form(cls, template_path): return dict(commitmessage=forms.CharField( widget=forms.TextInput(attrs={'size': '100'}), label=_('Change message'), required=False, ))
class Meta: model = Task fields = ['title', 'complete'] widgets = { 'title': forms.TextInput(attrs={'class': 'form-control'}), }
class BookForm(forms.ModelForm): ISBN = forms.CharField( label='ISBN', widget=forms.TextInput( attrs={ 'required': True, 'type':'number', 'class': 'form-control', 'placeholder': 'Введите ISBN = 13 чисел' } ) ) title = forms.CharField( label='Название книги', widget=forms.TextInput( attrs={ 'required': True, 'type': 'text', 'class': 'form-control', 'placeholder': 'Введите название книги' } ) ) description = forms.CharField( label='Описание книги', widget=forms.Textarea( attrs={ 'required': True, 'class': 'form-control', 'rows': '3', 'placeholder': 'Введите описание книги' } ) ) year_release = forms.CharField( label='Дата публикации', widget=forms.TextInput( attrs={ 'required': True, 'type': 'number', 'class': 'form-control', 'placeholder': 'Введите дату создания книги' } ) ) author = forms.ModelChoiceField( queryset=Author.objects.all(), label='Автор книги', widget=forms.Select( attrs={ 'required': True, 'class': 'form-control' } ) ) publisher = forms.ModelChoiceField( queryset=Publisher.objects.all(), label='Издательство', widget=forms.Select( attrs={ 'required': True, 'class': 'form-control' } ) ) copy_count = forms.CharField( label= 'Общее количество книг', widget= forms.TextInput( attrs={ 'required': True, 'type': 'number', 'class': 'form-control', 'placeholder': 'Введите общее количество книг' } ) ) price = forms.CharField( label= 'Цена книги', widget= forms.TextInput( attrs={ 'required': True, 'type': 'number', 'class': 'form-control', 'placeholder': 'Введите стоимость книги' } ) ) cover = forms.ImageField( label='Обложка', required=False, widget=MyClearableFileInput( attrs={ 'class': 'form-control', 'accept': '.jpg,.jpeg,.png,.gif' } ) ) class Meta: model = Book fields = ('ISBN', 'title', 'description', 'year_release', 'author', 'price', 'copy_count', 'publisher', 'cover')
class UserForm(forms.Form): username = forms.CharField(label="用戶名", max_length=128, widget=forms.TextInput(attrs={'class': 'form-control'})) password = forms.CharField(label="密碼", max_length=256, widget=forms.PasswordInput(attrs={'class': 'form-control'}))
class NodeStorageForm(SerializerForm): """ Create or update node storage. """ _api_call = node_storage node = forms.CharField( label=_('Node'), widget=forms.TextInput( attrs={ 'class': 'input-transparent narrow uneditable-input', 'disabled': 'disabled' })) zpool = forms.ChoiceField( label=_('Zpool'), widget=forms.Select( attrs={'class': 'narrow input-select2 disable_created2'})) alias = forms.CharField( label=_('Alias'), required=True, max_length=32, widget=forms.TextInput(attrs={ 'class': 'input-transparent narrow', 'required': 'required' })) type = forms.TypedChoiceField( label=_('Type'), required=False, coerce=int, choices=Storage.TYPE, widget=forms.Select(attrs={'class': 'input-select2 narrow'})) owner = forms.ChoiceField( label=_('Owner'), required=False, widget=forms.Select(attrs={'class': 'narrow input-select2'})) access = forms.TypedChoiceField( label=_('Access'), required=False, coerce=int, choices=Storage.ACCESS, widget=forms.Select(attrs={'class': 'input-select2 narrow'})) desc = forms.CharField(label=_('Description'), max_length=128, required=False, widget=forms.TextInput(attrs={ 'class': 'input-transparent wide', 'required': '' })) size_coef = forms.DecimalField( label=_('Size coefficient'), max_digits=4, decimal_places=2, help_text=_('Coefficient for calculating the maximum amount of ' 'disk space for virtual machines.'), widget=forms.TextInput(attrs={ 'class': 'input-transparent narrow', 'required': 'required' })) def __init__(self, request, node, ns, *args, **kwargs): super(NodeStorageForm, self).__init__(request, ns, *args, **kwargs) self.fields['owner'].choices = get_owners(request).values_list( 'username', 'username') node_zpools = node.zpools zpools = [(k, '%s (%s)' % (k, filesizeformat(int(v['size']) * 1048576))) for k, v in node_zpools.items()] # Add zpools for NodeStorage objects that have vanished from compute node (Issue #chili-27) for zpool in node.nodestorage_set.exclude( zpool__in=node_zpools.keys()).values_list('zpool', flat=True): zpools.append((zpool, '%s (???)' % zpool)) self.fields['zpool'].choices = zpools def _initial_data(self, request, obj): data = obj.web_data data['size_coef'] = obj.storage.size_coef return data
class SearchForm(forms.Form): url = forms.CharField(widget=forms.TextInput(attrs={'class': 'search', 'placeholder': 'Search URL'}),max_length=255)
class NodeForm(SerializerForm): """ Update compute node settings. """ _api_call = node_define hostname = forms.CharField( label=_('Hostname'), widget=forms.TextInput( attrs={ 'class': 'input-transparent narrow uneditable-input', 'disabled': 'disabled' })) owner = forms.ChoiceField( label=_('Owner'), widget=forms.Select(attrs={'class': 'narrow input-select2'})) status = forms.TypedChoiceField( label=_('Status'), choices=Node.STATUS, coerce=int, widget=forms.Select(attrs={'class': 'narrow input-select2'})) is_compute = forms.BooleanField( label=_('Compute?'), required=False, widget=forms.CheckboxInput(attrs={'class': 'normal-check'})) is_backup = forms.BooleanField( label=_('Backup?'), required=False, widget=forms.CheckboxInput(attrs={'class': 'normal-check'})) note = forms.CharField( label=_('Note'), help_text=_( 'Custom text information about this compute node, with markdown' ' support.'), required=False, widget=forms.Textarea(attrs={ 'class': 'input-transparent small', 'rows': 5 })) address = forms.ChoiceField( label=_('IP address'), help_text=_( 'IP address used for communication between compute nodes ' '(e.g., VM backups, VM replication, internal VM and node monitoring).' ), widget=forms.Select(attrs={'class': 'narrow input-select2'})) cpu_coef = forms.DecimalField( label=_('CPUs coefficient'), max_digits=4, decimal_places=2, help_text=_( 'Coefficient for calculating the the total number of virtual CPUs.' ), widget=forms.TextInput(attrs={ 'class': 'input-transparent narrow', 'required': 'required' })) ram_coef = forms.DecimalField( label=_('RAM coefficient'), max_digits=4, decimal_places=2, help_text=_('Coefficient for calculating the maximum amount of memory ' 'for virtual machines.'), widget=forms.TextInput(attrs={ 'class': 'input-transparent narrow', 'required': 'required' })) monitoring_templates = ArrayField( label=_('Monitoring templates'), required=False, tags=True, help_text=_('Comma-separated list of custom monitoring templates.'), widget=ArrayWidget(tags=True, escape_space=False, attrs={ 'class': 'tags-select2 narrow', 'data-tags-type': 'mon_templates', 'data-tags-api-call': 'mon_node_template_list' })) monitoring_hostgroups = ArrayField( label=_('Monitoring hostgroups'), required=False, tags=True, help_text=_('Comma-separated list of custom monitoring hostgroups.'), validators=[ RegexValidator(regex=MonitoringBackend.RE_MONITORING_HOSTGROUPS) ], widget=ArrayWidget(tags=True, escape_space=False, attrs={ 'class': 'tags-select2 narrow', 'data-tags-type': 'mon_hostgroups', 'data-tags-api-call': 'mon_node_hostgroup_list' })) def __init__(self, request, node, *args, **kwargs): super(NodeForm, self).__init__(request, node, *args, **kwargs) self.fields['owner'].choices = get_owners(request).values_list( 'username', 'username') self.fields['address'].choices = [(ip, ip) for ip in node.ips] dc1_settings = get_dc1_settings(request) if dc1_settings.MON_ZABBIX_HOSTGROUPS_NODE: self.fields['monitoring_hostgroups'].help_text += _(' Automatically added hostgroups: ') \ + ', '.join(dc1_settings.MON_ZABBIX_HOSTGROUPS_NODE) if node.is_unlicensed(): self.fields['status'].choices = Node.STATUS_DB self.fields['status'].widget.attrs['disabled'] = 'disabled' elif node.is_unreachable(): self.fields['status'].choices = Node.STATUS_DB[:-1] self.fields['status'].widget.attrs['disabled'] = 'disabled' def _initial_data(self, request, obj): return obj.web_data
class Meta: fields = ['name', 'default'] widgets = { 'default': forms.TextInput() }