class UpdateProfileForm(forms.ModelForm): gender = forms.SelectMultiple() country = forms.CharField(label='Country', widget=forms.TextInput( attrs={ 'placeholder': 'Country', 'class': 'form-control', })) region = forms.CharField(label='Region', widget=forms.TextInput( attrs={ 'placeholder': 'Region', 'class': 'form-control', })) address1 = forms.CharField(label='Address 1', widget=forms.TextInput( attrs={ 'placeholder': 'Address 1', 'class': 'form-control', })) address2 = forms.CharField(label='Address 2', required=False, widget=forms.TextInput( attrs={ 'placeholder': 'Address 2', 'class': 'form-control', })) phone_number1 = forms.CharField(label='Phone Number 1', widget=forms.TextInput( attrs={ 'placeholder': 'Phone Number 1', 'class': 'form-control', })) phone_number2 = forms.CharField(label='Phone Number 2', required=False, widget=forms.TextInput( attrs={ 'placeholder': 'Phone Number 2', 'class': 'form-control', })) comments = forms.CharField(label='Comments', widget=forms.Textarea( attrs={ 'placeholder': 'Comments', 'class': 'form-control', })) image = forms.ImageField(label='Image') class Meta: model = Account fields = [ 'gender', 'country', 'image', 'region', 'address1', 'address2', 'phone_number1', 'phone_number2', 'comments', ] def clean(self, *args, **kwargs): gender = self.cleaned_data.get('gender') country = self.cleaned_data.get('country') region = self.cleaned_data.get('region') address1 = self.cleaned_data.get('address1') phone_number1 = self.cleaned_data.get('phone_number1') phone_number2 = self.cleaned_data.get('phone_number2') if not gender: raise forms.ValidationError('Please select your gender!') if not country: raise forms.ValidationError('Please enter your country!') if not region: raise forms.ValidationError('Please enter your region!') if not address1: raise forms.ValidationError('Please enter your address1!') if not phone_number1: raise forms.ValidationError('Please enter your phone number1!') if not phone_number2: raise forms.ValidationError('Please enter your phone number2!') return super(UpdateProfileForm, self).clean(*args, **kwargs)
class AssetBulkUpdateForm(OrgModelForm): assets = forms.ModelMultipleChoiceField( required=True, label=_('Select assets'), queryset=Asset.objects.all(), widget=forms.SelectMultiple(attrs={ 'class': 'select2', 'data-placeholder': _('Select assets') })) class Meta: model = Asset fields = [ 'assets', 'admin_user', 'labels', 'platform', 'domain', ] widgets = { 'labels': forms.SelectMultiple(attrs={ 'class': 'select2', 'data-placeholder': _('Label') }), 'nodes': forms.SelectMultiple(attrs={ 'class': 'select2', 'data-placeholder': _('Node') }), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # 重写其他字段为不再required for name, field in self.fields.items(): if name != 'assets': field.required = False def save(self, commit=True): changed_fields = [] for field in self._meta.fields: if self.data.get(field) not in [None, '']: changed_fields.append(field) cleaned_data = { k: v for k, v in self.cleaned_data.items() if k in changed_fields } assets = cleaned_data.pop('assets') labels = cleaned_data.pop('labels', []) nodes = cleaned_data.pop('nodes', None) assets = Asset.objects.filter(id__in=[asset.id for asset in assets]) assets.update(**cleaned_data) if labels: for asset in assets: asset.labels.set(labels) if nodes: for asset in assets: asset.nodes.set(nodes) return assets
class AdminUserForm(forms.ModelForm): # Admin user assets define, let user select, save it in form not in view assets = forms.ModelMultipleChoiceField( queryset=Asset.objects.all(), label=_('Asset'), required=False, widget=forms.SelectMultiple(attrs={ 'class': 'select2', 'data-placeholder': _('Select assets') })) # Form field name can not start with `_`, so redefine it, password = forms.CharField( widget=forms.PasswordInput, max_length=100, min_length=8, strip=True, required=False, help_text=_('If also set private key, use that first'), ) # Need use upload private key file except paste private key content private_key_file = forms.FileField(required=False) def __init__(self, *args, **kwargs): # When update a admin user instance, initial it if kwargs.get('instance'): initial = kwargs.get('initial', {}) initial['assets'] = kwargs['instance'].assets.all() super(AdminUserForm, self).__init__(*args, **kwargs) def _save_m2m(self): # Save assets relation with admin user super(AdminUserForm, self)._save_m2m() assets = self.cleaned_data['assets'] self.instance.assets.clear() self.instance.assets.add(*tuple(assets)) def save(self, commit=True): # Because we define custom field, so we need rewrite :method: `save` admin_user = super(AdminUserForm, self).save(commit=commit) password = self.cleaned_data['password'] private_key = self.cleaned_data['private_key_file'] if password: admin_user.password = password if private_key: public_key = ssh_pubkey_gen(private_key) admin_user.private_key = private_key admin_user.public_key = public_key admin_user.save() return admin_user def clean_private_key_file(self): private_key_file = self.cleaned_data['private_key_file'] if private_key_file: private_key = private_key_file.read() if not validate_ssh_private_key(private_key): raise forms.ValidationError(_('Invalid private key')) return private_key return private_key_file def clean(self): password = self.cleaned_data['password'] private_key_file = self.cleaned_data.get('private_key_file', '') if not self.instance and not (password or private_key_file): raise forms.ValidationError( _('Password and private key file must be input one')) class Meta: model = AdminUser fields = [ 'name', 'username', 'password', 'private_key_file', 'comment' ] widgets = { 'name': forms.TextInput(attrs={'placeholder': _('Name')}), 'username': forms.TextInput(attrs={'placeholder': _('Username')}), } help_texts = { 'name': '* required', 'username': '******', }
class FilterForm(forms.Form): SORT_CHOICES = ( ('-social_account__subscribers', { 'label': _('subscribers'), 'data-imagesrc': static('smmpay/images/sort_higher.png') }), ('social_account__subscribers', { 'label': _('subscribers'), 'data-imagesrc': static('smmpay/images/sort_lower.png') }), ('-price', { 'label': _('price min'), 'data-imagesrc': static('smmpay/images/sort_higher.png') }), ('price', { 'label': _('price min'), 'data-imagesrc': static('smmpay/images/sort_lower.png') }), ('-views', _('popularity')), ) search_query = forms.CharField( label=_('Search'), required=False, widget=forms.TextInput(attrs={ 'class': 'filter__search', 'placeholder': _("For example 'sport'") })) category = forms.MultipleChoiceField( label=_('Category'), required=False, widget=forms.SelectMultiple(attrs={'multiple': 'multiple'})) service = forms.MultipleChoiceField( label=_('Advertising services'), required=False, widget=forms.SelectMultiple(attrs={'multiple': 'multiple'})) price = forms.IntegerField( label=_('Price, from'), required=False, widget=forms.TextInput(attrs={'class': 'filter__value'})) subscribers_min = forms.IntegerField( label=_('Subscribers, from'), required=False, widget=forms.TextInput(attrs={'class': 'filter__value'})) subscribers_max = forms.IntegerField( label=_('Subscribers, to'), required=False, widget=forms.TextInput(attrs={'class': 'filter__value'})) sort_by = forms.ChoiceField(label=_('Sort by'), required=False, choices=SORT_CHOICES, initial=SORT_CHOICES[0][0], widget=SelectWithOptionAttrs(attrs={ 'class': 'filter__select', 'id': 'sort_by' })) def __init__(self, selected_social_network, *args, **kwargs): super(FilterForm, self).__init__(*args, **kwargs) self.fields['category'].choices = Category.objects.values_list( 'slug', 'title') if selected_social_network is not None: self.fields[ 'service'].choices = SocialNetworkService.objects.filter( social_network=selected_social_network).values_list( 'pk', 'title')
class Meta: model = models.Application fields = ['data_elements'] widgets = { 'data_elements': forms.SelectMultiple(attrs={'size': 15}) }
class PhotoTagsForm(forms.ModelForm): country_index = forms.ModelChoiceField(queryset=CountryIndex.objects.all(), required=False, label="Where was this picture taken?") park = forms.ModelChoiceField(queryset=Park.objects.all(), required=False, label="Park / game reserve?") activity = forms.ModelChoiceField(queryset=Activity.objects.filter(activity_type="SAFARI"), required=False, label="What were you doing?") animals = forms.ModelMultipleChoiceField( label="Any animals in the photo?", required=False, widget=forms.SelectMultiple(attrs={'class': "select2"}), queryset=Animal.objects.all().order_by('name'), ) tags = TagsInputField(queryset=Tag.objects.all(), label="Additional tags (example: sunset, jeep)", required=False) class Meta: model = Photo fields = ('country_index', 'park', 'activity', 'animals', 'tags') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.data.get('country_index',''): self.fields['park'].queryset = Park.objects.filter(country_indexes__id=self.data['country_index']) else: if self.instance.country_index: self.fields['park'].queryset = Park.objects.filter(country_indexes__id=self.instance.country_index.id) else: self.fields['park'].queryset = Park.objects.none() self.helper = FormHelper() self.helper.layout = Layout( Div( Div( Div( 'country_index', css_class="col-12 col-md-6" ), Div( 'park', css_class="col-12 col-md-6" ), css_class="row" ), Div( Div( 'activity', css_class="col-12 col-md-6" ), css_class="row" ), Div( Div( 'animals', css_class="col-12" ), css_class="row" ), Div( Div( 'tags', css_class="col-12" ), css_class="row" ), css_class="container" ), ButtonHolder( Submit('submit', 'Submit', css_class='button white'), HTML('<a class="cancel" id="cancel_button">Cancel</a>') ) )
class AssetBulkUpdateForm(forms.ModelForm): assets = forms.ModelMultipleChoiceField( required=True, help_text='* required', label=_('Select assets'), queryset=Asset.objects.all(), widget=forms.SelectMultiple(attrs={ 'class': 'select2', 'data-placeholder': _('Select assets') })) port = forms.IntegerField( label=_('Port'), required=False, min_value=1, max_value=65535, ) admin_user = forms.ModelChoiceField( required=False, queryset=AdminUser.objects.all(), label=_("Admin user"), widget=forms.Select(attrs={ 'class': 'select2', 'data-placeholder': _('Admin user') })) class Meta: model = Asset fields = [ 'assets', 'port', 'admin_user', 'labels', 'nodes', 'platform' ] widgets = { 'labels': forms.SelectMultiple(attrs={ 'class': 'select2', 'data-placeholder': _('Label') }), 'nodes': forms.SelectMultiple(attrs={ 'class': 'select2', 'data-placeholder': _('Node') }), } def save(self, commit=True): changed_fields = [] for field in self._meta.fields: if self.data.get(field) not in [None, '']: changed_fields.append(field) cleaned_data = { k: v for k, v in self.cleaned_data.items() if k in changed_fields } assets = cleaned_data.pop('assets') labels = cleaned_data.pop('labels', []) nodes = cleaned_data.pop('nodes') assets = Asset.objects.filter(id__in=[asset.id for asset in assets]) assets.update(**cleaned_data) if labels: for label in labels: label.assets.add(*tuple(assets)) if nodes: for node in nodes: node.assets.add(*tuple(assets)) return assets
class HostBaseForm(forms.ModelForm): # status = forms.CharField(required=True,disabled=True) manage_ip = forms.CharField(required=False, max_length=15, label=u"管理IP") outer_ip = forms.CharField(required=False, max_length=15, label=u"外网IP") coreness = forms.CharField(required=False, max_length=5, label=u"CPU核数") memory = forms.CharField(required=False, max_length=7, label=u"内存大小") root_disk = forms.CharField(required=False, max_length=7, label=u"本地磁盘") service_ip = forms.CharField(required=True, max_length=15, label=u"服务IP") groups = forms.ModelMultipleChoiceField( required=False, queryset=models.Group.objects.all(), to_field_name="id", widget=forms.SelectMultiple(attrs={'class': 'select2'}), label=u'应用组') storages = forms.ModelMultipleChoiceField( required=False, queryset=models.Storage.objects.all(), to_field_name="id", widget=forms.SelectMultiple(attrs={'class': 'select2'}), label=u'存储') systemtype = forms.ModelChoiceField( required=True, queryset=models.System_Type.objects.all(), to_field_name="id", widget=forms.Select(attrs={'class': 'select2'}), label=u'操作系统') class Meta: model = models.Host fields = [ 'systemtype', 'manage_ip', 'service_ip', 'outer_ip', 'server_position', 'hostname', 'normal_user', 'sshport', 'coreness', 'memory', 'root_disk', 'info', 'sshpasswd', 'storages', 'groups', ] widgets = { 'info': forms.Textarea(attrs=None), 'sshpasswd': forms.TextInput(attrs={'type': 'password'}), } labels = { 'sshport': '管理端口', 'server_position': '服务器位置', 'hostname': '主机名称', 'normal_user': '******', 'info': '信息', 'sshpasswd': '管理密码', } def clean_sshpasswd(self): sshpasswd = self.cleaned_data['sshpasswd'] if checkpass.checkPassword(sshpasswd): return aes.encrypt(sshpasswd) else: raise forms.ValidationError(u'密码复杂度不足')
def __init__(self, *args, **kwargs): yaml_layout = kwargs.pop('yaml_layout') q_field = Div( FieldWithButtons( Field('q', placeholder=_('Filtrar Lista'), autocomplete='off', type='search', onkeypress='atualizaContatos(event)'), StrictButton(_('Filtrar'), css_class='btn-default', type='button', onclick='atualizaContatos(event)')), Div(css_class='form-group-contato-search')) q = [ _('Seleção de Contatos'), [(q_field, 5), (Div(Field('contatos'), css_class='form-group-contatos'), 7)] ] yaml_layout.append(q) self.helper = FormHelper() self.helper.layout = SaplFormLayout(*yaml_layout) super(ProcessoForm, self).__init__(*args, **kwargs) if not self.instance.pk: self.fields['data'].initial = date.today() self.fields['q'].help_text = _('Digite parte do nome, nome social ou ' 'apelido do Contato que você procura.') self.fields['topicos'].widget = forms.SelectMultiple( attrs={'size': '8'}) self.fields['topicos'].queryset = TopicoProcesso.objects.all() self.fields['assuntos'].widget = forms.SelectMultiple( attrs={'size': '8'}) self.fields['assuntos'].queryset = AssuntoProcesso.objects.filter( workspace=self.initial['workspace']) # Utilizando template bootstrap3 customizado self.fields['importancia'].widget = forms.RadioSelect() self.fields['importancia'].inline_class = True self.fields['importancia'].choices = IMPORTANCIA_CHOICE self.fields['status'].widget = forms.RadioSelect() # self.fields['status'].inline_class = True self.fields['status'].choices = [ (ass.pk, ass) for ass in StatusProcesso.objects.order_by('id') ] self.fields['classificacoes'].widget = forms.CheckboxSelectMultiple() # self.fields['classificacoes'].inline_class = True self.fields['contatos'].widget = forms.CheckboxSelectMultiple() self.fields['contatos'].queryset = Contato.objects.all() self.fields['contatos'].choices = [ (c.pk, c) for c in self.instance.contatos.order_by('nome')]\ if self.instance.pk else [] self.fields['contatos'].help_text = _( 'Procure por Contatos na caixa de buscas e arraste ' 'para esta caixa os Contatos interessados neste Processo.')
class Meta: model = Project exclude = ("id", ) widgets = { 'name': TextInput(attrs={ 'class': 'form-control', 'style': 'width:450px;' }), 'description': Textarea(attrs={ 'class': 'form-control', 'style': 'width:450px; height:100px' }), 'language_type': Select(attrs={ 'class': 'form-control', 'style': 'width:450px;' }), 'app_type': Select(attrs={ 'class': 'form-control', 'style': 'width:450px;' }), 'server_type': Select(attrs={ 'class': 'form-control', 'style': 'width:450px;' }), 'app_arch': Select(attrs={ 'class': 'form-control', 'style': 'width:450px;' }), 'appPath': TextInput(attrs={ 'class': 'form-control', 'style': 'width:450px;' }), 'source_type': Select(attrs={ 'class': 'form-control', 'style': 'width:450px;' }), 'source_address': TextInput(attrs={ 'class': 'form-control', 'style': 'width:450px;' }), 'configPath': TextInput(attrs={ 'class': 'form-control', 'style': 'width:450px;' }), 'product': Select(attrs={ 'class': 'form-control', 'style': 'width:450px;' }), 'owner': Select(attrs={ 'class': 'form-control', 'style': 'width:450px;' }), 'serverList': forms.SelectMultiple(attrs={ 'class': 'form-control', 'size': '10', 'multiple': 'multiple' }), }
class TabGenerationOptionsForm(forms.Form): def __init__(self, *args, **kwargs): super(TabGenerationOptionsForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Div(Div(HTML('<h3>Generation Options</h3>'), css_class='col-md-9'), Div(FormActions( Submit('submit', 'Generate', style="margin-top: 20px;")), css_class='col-md-3'), css_class='row'), Div( Div( Accordion( AccordionGroup('Expansion Selection', 'expansions', 'fan_expansions'), AccordionGroup( 'Page Options', 'pagesize', HTML( "Selecting Labels will override some settings to fit the size of the label" ), 'no_footer', AppendedText('back_offset', 'points', active=True), AppendedText('back_offset_height', 'points', active=True)), AccordionGroup( 'Style Options', 'orientation', 'wrappers', 'notch', 'linetype', 'cardsize', AppendedText('horizontal_gap', 'cm', active=True), AppendedText('vertical_gap', 'cm', active=True)), AccordionGroup( 'Tab Options', 'tab_number', 'tab_side', 'serpentine', 'reset_tabs', 'tab_name_align', 'set_icon', 'cost_icon', 'black_tabs', AppendedText('tabwidth', 'cm', active=True)), AccordionGroup('Body Options', 'counts', 'types', 'divider_front_text', 'divider_back_text', 'language'), AccordionGroup('Order, Groups and Extras', 'order', 'group_special', 'base_cards_with_expansion', 'upgrade_with_expansion', 'events', 'expansion_dividers', 'centre_expansion_dividers', 'expansion_dividers_long_name'), ), css_class='col-md-12', ), 'tag', css_class='row', )) self.helper.form_id = 'id-tabgenoptions' self.helper.form_class = 'blueForms' self.helper.form_method = 'post' self.helper.form_action = '/' for field in self.fields.values(): field.required = False choices = ['Horizontal', 'Vertical'] orientation = forms.ChoiceField(choices=list(zip(choices, choices)), label='Divider Orientation', initial='Horizontal') pagesize = forms.ChoiceField(choices=list( zip(PAPER_SIZES + domdiv.main.LABEL_KEYS, PAPER_SIZES + domdiv.main.LABEL_SELECTIONS)), label='Paper Type', initial='Letter') choices = ['Sleeved - Thin', 'Sleeved - Thick', 'Unsleeved'] cardsize = forms.ChoiceField(choices=list(zip(choices, choices)), label='Card Size', initial='Unsleeved') tabwidth = forms.FloatField(label='Width of Tab in centimeters', initial='4.0', required=False, widget=forms.TextInput()) back_offset = forms.FloatField( label='Back page horizontal offset points to shift to the right', initial='0', required=False, widget=forms.TextInput()) back_offset_height = forms.FloatField( label='Back page vertical offset points to shift upward', initial='0', required=False, widget=forms.TextInput()) horizontal_gap = forms.FloatField( label='Horizontal gap between dividers in centimeters', initial='0', required=False, widget=forms.TextInput()) vertical_gap = forms.FloatField( label='Vertical gap between dividers in centimeters', initial='0', required=False, widget=forms.TextInput()) black_tabs = forms.BooleanField(label='Black tab background', initial=False) # Expansions choices = domdiv.main.EXPANSION_CHOICES # make pretty names for the expansion choices choiceNames = [] replacements = { '1stedition': '1st Edition', '2ndeditionupgrade': '2nd Edition Upgrade', '2ndedition': '2nd Edition' } for choice in choices: for s, r in replacements.items(): if choice.lower().endswith(s): choiceNames.append('{} {}'.format( choice[:-len(s)].capitalize(), r)) break else: choiceNames.append(choice.capitalize()) expansions = forms.MultipleChoiceField( choices=list(zip(choices, choiceNames)), label='Expansions to Include (Cmd/Ctrl click to select multiple)', initial=choices, widget=forms.SelectMultiple(attrs={'size': '18'})) # Now Fan expansions choices = domdiv.main.FAN_CHOICES # make pretty names for the expansion choices choiceNames = [] for choice in choices: for s, r in replacements.items(): if choice.lower().endswith(s): choiceNames.append('{} {}'.format( choice[:-len(s)].capitalize(), r)) break else: choiceNames.append(choice.capitalize()) fan_expansions = forms.MultipleChoiceField( choices=list(zip(choices, choiceNames)), label='Fan Expansions to Include (Cmd/Ctrl click to select multiple)', initial='', widget=forms.SelectMultiple(attrs={'size': '3'})) base_cards_with_expansion = forms.BooleanField( label="Include Base cards with the expansion", initial=False) upgrade_with_expansion = forms.BooleanField( label="Include upgrade cards with the expansion being upgraded", initial=False) edition = forms.ChoiceField(choices=list( zip(domdiv.main.EDITION_CHOICES, domdiv.main.EDITION_CHOICES)), label='Edition', initial='latest') cropmarks = forms.BooleanField(label="Cropmarks Instead of Outlines", initial=False) linetype = forms.ChoiceField(choices=list( zip(domdiv.main.LINE_CHOICES, domdiv.main.LINE_CHOICES)), label='Outline Type', initial='line') wrappers = forms.BooleanField(label="Slipcases Instead of Dividers", initial=False) notch = forms.BooleanField(label="If Slipcases, add a notch in corners", initial=False) serpentine = forms.BooleanField( label= "For 3 or more tabs, tab location reverses when the end is reached instead of resetting to the start", initial=False) reset_tabs = forms.BooleanField( label="Restart tab starting location with every expansion.", initial=True) counts = forms.BooleanField(label="Show number of Cards per Divider", initial=False) types = forms.BooleanField(label="Show Card Type on each Divider", initial=False) tab_name_align = forms.ChoiceField(choices=list( zip(domdiv.main.NAME_ALIGN_CHOICES, domdiv.main.NAME_ALIGN_CHOICES))) tab_number = forms.ChoiceField(choices=list( zip([x for x in TAB_NUMBER_SELECTION], [TAB_NUMBER_SELECTION[x] for x in TAB_NUMBER_SELECTION])), label='Number of tabs', initial=1) for x in domdiv.main.TAB_SIDE_CHOICES: if x not in TAB_SIDE_SELECTION: TAB_SIDE_SELECTION[x] = x.title() tab_side = forms.ChoiceField(choices=list( zip([x for x in TAB_SIDE_SELECTION], [TAB_SIDE_SELECTION[x] for x in TAB_SIDE_SELECTION])), label='Starting tab location', initial='left') samesidelabels = forms.BooleanField(label="Same Side Labels", initial=False) order = forms.ChoiceField(label="Divider Order", choices=list( zip(domdiv.main.ORDER_CHOICES, domdiv.main.ORDER_CHOICES))) group_special = forms.BooleanField( label="Group Special Cards (e.g. Prizes)", initial=True) expansion_dividers = forms.BooleanField(label="Include Expansion Dividers", initial=False) centre_expansion_dividers = forms.BooleanField( label="If Expansion Dividers, centre the tabs on expansion dividers", initial=False) expansion_dividers_long_name = forms.BooleanField( label=("If Expansion Dividers, use edition " "on expansion dividers names"), initial=False) set_icon = forms.ChoiceField(choices=list( zip(domdiv.main.LOCATION_CHOICES, domdiv.main.LOCATION_CHOICES)), label="Set Icon Location", initial="tab") cost_icon = forms.ChoiceField(choices=list( zip(domdiv.main.LOCATION_CHOICES, domdiv.main.LOCATION_CHOICES)), label="Cost Icon Location", initial="tab") language = forms.ChoiceField(choices=list( zip(domdiv.main.LANGUAGE_CHOICES, domdiv.main.LANGUAGE_CHOICES)), label='Language', initial='en_us') events = forms.BooleanField(label="Exclude Individual Events & Landmarks", initial=False) divider_front_text = forms.ChoiceField(label='Front Text', choices=list( zip(domdiv.main.TEXT_CHOICES, domdiv.main.TEXT_CHOICES)), initial='card') divider_back_text = forms.ChoiceField( label='Back Text', choices=list( zip(domdiv.main.TEXT_CHOICES + ['none'], domdiv.main.TEXT_CHOICES + ['no back page'])), initial='rules') no_footer = forms.BooleanField( label='Omit the expansion name at the bottom of the page', initial=False) tag = forms.CharField(widget=forms.HiddenInput(), initial='domdiv')
def report(request, report_id, template_name="report/report.html"): if request.user.is_staff: rtype = get_object_or_404(ReportType, id=report_id) if not request.user.is_superuser: if rtype.permissao.count() and not len([ val for val in rtype.permissao.all() if val in request.user.groups.all() ]): raise Http404 rtadmin = admin.site._registry[rtype.modelo.model_class()] campos_dinamicos = {} for filtro in rtadmin.list_filter: field = get_field(rtype.modelo.model_class(), filtro) if type(field) == models.BooleanField: choices = (('1', _(u'Sim')), ('0', _(u'Não')), ('', _(u'Todos'))) campos_dinamicos[filtro] = forms.ChoiceField( required=False, choices=choices, label=_(field.verbose_name), widget=forms.RadioSelect()) elif type(field) == models.CharField: if field.choices: choices = field.choices campos_dinamicos[filtro] = forms.MultipleChoiceField( required=False, choices=choices, label=_(field.verbose_name), widget=forms.CheckboxSelectMultiple()) else: choices = set() for obj in rtype.modelo.model_class().objects.all(): choices.add( (get_value(obj, filtro), get_value(obj, filtro))) choices = list(choices) campos_dinamicos[filtro] = forms.MultipleChoiceField( required=False, choices=choices, label=_(field.verbose_name), widget=forms.SelectMultiple()) elif type(field) == models.DateField or type( field) == models.DateTimeField: choices = (('q', _(u'Qualquer data')), ('h', _(u'Hoje')), ('m', _(u'Este mês')), ('a', _(u'Este ano'))) campos_dinamicos[filtro] = forms.ChoiceField( required=False, choices=choices, initial='q', label=_(field.verbose_name), widget=forms.RadioSelect()) elif type(field) == models.ForeignKey or type( field) == models.OneToOneField: queryset = rtype.modelo.model_class()._meta.get_field( filtro).rel.to.objects.all() campos_dinamicos[filtro] = forms.ModelMultipleChoiceField( required=False, queryset=queryset, label=_(field.verbose_name), widget=forms.SelectMultiple()) else: choices = set() for obj in rtype.modelo.model_class().objects.all(): choices.add((get_value(obj, filtro), get_value(obj, filtro))) choices = list(choices) campos_dinamicos[filtro] = forms.MultipleChoiceField( required=False, choices=choices, label=_(field.verbose_name), widget=forms.SelectMultiple()) FilterForm = type('', (forms.Form, ), campos_dinamicos) if request.method == "POST": response = HttpResponse(mimetype='application/pdf') response[ 'Content-Disposition'] = 'attachment; filename=%s.pdf' % smart_str( rtype.titulo).replace(" ", "_") queryset = rtype.modelo.model_class().objects.all() for field_name in rtadmin.list_filter: field = get_field(rtype.modelo.model_class(), field_name) sql = {} if type(field) == models.DateField or type( field) == models.DateTimeField: try: value = request.POST[field_name] if value == 'q': pass elif value == 'h': sql["%s__day" % field_name] = datetime.now().day elif value == 'm': sql["%s__month" % field_name] = datetime.now().month elif value == 'a': sql["%s__year" % field_name] = datetime.now().year except: pass elif type(field) == models.BooleanField: try: value = request.POST[field_name] sql["%s" % field_name] = value except: pass else: try: value = request.POST.getlist(field_name) if len(value) == 0: continue sql["%s__in" % field_name] = value except: pass query = models.Q(**sql) queryset = queryset.filter(query) campos = rtype.campos.replace('[', '').replace(']', '').replace( 'u\'', '').replace('\'', '').replace(',', '').split(' ') list_report = [] for c in campos: list_report.append(rtadmin.list_report[get_key(c)]) html = html_report_generic(smart_str(rtype.cabecalho), list_report, queryset) pdf = pisa.CreatePDF(html, response) return response else: form = FilterForm() return render_to_response(template_name, { 'form': form, 'title': rtype.titulo, 'rtype': rtype, 'rtadmin': rtadmin, }, context_instance=RequestContext(request)) else: raise PermissionDenied
class SearchForm(forms.Form): name = forms.CharField(required=False, widget=forms.TextInput(attrs={'class': 'span12'})) address = forms.CharField( required=False, widget=forms.TextInput(attrs={ 'class': 'span12', 'title': TooltipContent.empty_field, }), label="Address or network") remarks = forms.CharField( required=False, widget=forms.TextInput(attrs={ 'class': 'span12', 'title': TooltipContent.empty_field })) role = forms.CharField( required=False, widget=forms.TextInput(attrs={ 'class': 'span12', 'title': TooltipContent.empty_field, }), label="Venture or role") model = forms.CharField( required=False, widget=forms.TextInput(attrs={ 'class': 'span12', 'title': TooltipContent.empty_field_venture, })) component = forms.CharField( required=False, widget=forms.TextInput(attrs={'class': 'span12'}), label="Component") software = forms.CharField( required=False, widget=forms.TextInput(attrs={ 'class': 'span12', 'title': TooltipContent.software_field, }), label="Software") serial = forms.CharField( required=False, widget=forms.TextInput(attrs={ 'class': 'span12', 'title': TooltipContent.empty_field, }), label="Serial number, MAC or WWN") barcode = forms.CharField( required=False, widget=forms.TextInput(attrs={ 'class': 'span12', 'title': TooltipContent.empty_field, })) position = forms.CharField( required=False, widget=forms.TextInput(attrs={ 'class': 'span12', 'title': TooltipContent.empty_field, }), label="Datacenter, rack or position") history = forms.CharField( required=False, widget=forms.TextInput(attrs={'class': 'span12'})) device_type = forms.MultipleChoiceField( required=False, widget=forms.SelectMultiple(attrs={'class': 'span12'}), choices=DeviceType(item=lambda e: (e.id, e.raw)), ) device_group = forms.IntegerField(required=False, widget=DeviceGroupWidget, label="") component_group = forms.IntegerField(required=False, widget=ComponentGroupWidget, label="") purchase_date_start = forms.DateField( required=False, widget=DateWidget( attrs={ 'class': 'span12', 'placeholder': 'Start YYYY-MM-DD', 'data-collapsed': True, }), label='Purchase date', input_formats=['%Y-%m-%d']) purchase_date_end = forms.DateField( required=False, widget=DateWidget( attrs={ 'class': 'span12 end-date-field', 'placeholder': 'End YYYY-MM-DD', 'data-collapsed': True, }), label='', input_formats=['%Y-%m-%d']) no_purchase_date = forms.BooleanField( required=False, label="Empty purchase date", widget=forms.CheckboxInput(attrs={ 'data-collapsed': True, })) deprecation_date_start = forms.DateField( required=False, widget=DateWidget( attrs={ 'class': 'span12', 'placeholder': 'Start YYYY-MM-DD', 'data-collapsed': True, }), label='Deprecation date', input_formats=['%Y-%m-%d']) deprecation_date_end = forms.DateField( required=False, widget=DateWidget( attrs={ 'class': 'span12 end-date-field', 'placeholder': 'End YYYY-MM-DD', 'data-collapsed': True, }), label='', input_formats=['%Y-%m-%d']) no_deprecation_date = forms.BooleanField( required=False, label="Empty deprecation date", widget=forms.CheckboxInput(attrs={ 'data-collapsed': True, })) deprecation_kind = forms.MultipleChoiceField( required=False, widget=forms.SelectMultiple(attrs={ 'class': 'span12', 'data-collapsed': True }, ), label="Deprecation", choices=[('None', '-----')] + [(kind.id, kind.name) for kind in DeprecationKind.objects.all()], ) warranty_expiration_date_start = forms.DateField( required=False, widget=DateWidget( attrs={ 'class': 'span12', 'placeholder': 'Start YYYY-MM-DD', 'data-collapsed': True, }), label='Warranty expiration date', input_formats=['%Y-%m-%d']) warranty_expiration_date_end = forms.DateField( required=False, widget=DateWidget( attrs={ 'class': 'span12 end-date-field', 'placeholder': 'End YYYY-MM-DD', 'data-collapsed': True, }), label='', input_formats=['%Y-%m-%d']) no_warranty_expiration_date = forms.BooleanField( required=False, label="Empty warranty expiration date", widget=forms.CheckboxInput(attrs={ 'data-collapsed': True, })) support_expiration_date_start = forms.DateField( required=False, widget=DateWidget( attrs={ 'class': 'span12', 'placeholder': 'Start YYYY-MM-DD', 'data-collapsed': True, }), label='Support expiration date', input_formats=['%Y-%m-%d']) support_expiration_date_end = forms.DateField( required=False, widget=DateWidget( attrs={ 'class': 'span12 end-date-field ', 'placeholder': 'End YYYY-MM-DD', 'data-collapsed': True, }), label='', input_formats=['%Y-%m-%d']) no_support_expiration_date = forms.BooleanField( required=False, label="Empty support expiration date", widget=forms.CheckboxInput(attrs={ 'data-collapsed': True, })) deleted = forms.BooleanField(required=False, label="Include deleted") def clean_purchase_date_end(self): validate_start_end_date_date(self.cleaned_data['purchase_date_start'], self.cleaned_data['purchase_date_end']) return self.cleaned_data['purchase_date_end'] def clean_deprecation_date_end(self): validate_start_end_date_date( self.cleaned_data['deprecation_date_start'], self.cleaned_data['deprecation_date_end']) return self.cleaned_data['deprecation_date_end'] def clean_warranty_expiration_date_end(self): validate_start_end_date_date( self.cleaned_data['warranty_expiration_date_start'], self.cleaned_data['warranty_expiration_date_end']) return self.cleaned_data['warranty_expiration_date_end'] def clean_support_expiration_date_end(self): validate_start_end_date_date( self.cleaned_data['support_expiration_date_start'], self.cleaned_data['support_expiration_date_end']) return self.cleaned_data['support_expiration_date_end'] def clean_address(self): data = self.cleaned_data['address'] if data: if '/' in data: try: ipaddr.IPNetwork(data) except ValueError: raise forms.ValidationError("Invalid network") else: try: ipaddr.IPv4Address(data) except ValueError: raise forms.ValidationError("Invalid address") return data
def __init__(self, *args, **kwargs): super(BuscarUsuario, self).__init__(*args, **kwargs) lista=getSelect('all') lista2=getSelect(args[0]["grupo"]) lista3 = [x for x in lista if x not in lista2] self.fields['usuarios']=forms.MultipleChoiceField(choices=lista3,required=False,widget=forms.SelectMultiple(attrs={'class': "form-control js-example-basic-multiple"}))
class ReviewForm(happyforms.Form): comments = forms.CharField(required=True, widget=forms.Textarea(), label=_(u'Comments:')) canned_response = NonValidatingChoiceField(required=False) action = forms.ChoiceField(required=True, widget=forms.RadioSelect()) versions = ModelMultipleChoiceField( widget=forms.SelectMultiple(attrs={ 'class': 'data-toggle', 'data-value': 'reject_multiple_versions|' }), required=False, queryset=Version.objects.none()) # queryset is set later in __init__. operating_systems = forms.CharField(required=False, label=_(u'Operating systems:')) applications = forms.CharField(required=False, label=_(u'Applications:')) notify = forms.BooleanField(required=False, label=_(u'Notify me the next time this ' u'add-on is updated. (Subsequent ' u'updates will not generate an ' u'email)')) adminflag = forms.BooleanField(required=False, label=_(u'Clear Admin Review Flag')) info_request = forms.BooleanField(required=False, label=_(u'Is more info requested?')) def is_valid(self): # Some actions do not require comments. action = self.helper.actions.get(self.data.get('action')) if action: if not action.get('comments', True): self.fields['comments'].required = False if action.get('versions', False): self.fields['versions'].required = True result = super(ReviewForm, self).is_valid() if result: self.helper.set_data(self.cleaned_data) return result def __init__(self, *args, **kw): self.helper = kw.pop('helper') self.type = kw.pop('type', amo.CANNED_RESPONSE_ADDON) super(ReviewForm, self).__init__(*args, **kw) # With the helper, we now have the add-on and can set queryset on the # versions field correctly. Small optimization: we only need to do this # if the reject_multiple_versions action is available, otherwise we # don't really care about this field. if 'reject_multiple_versions' in self.helper.actions: self.fields['versions'].queryset = ( self.helper.addon.versions.distinct().filter( channel=amo.RELEASE_CHANNEL_LISTED, files__status=amo.STATUS_PUBLIC).order_by('created')) # For the canned responses, we're starting with an empty one, which # will be hidden via CSS. canned_choices = [[ '', [('', ugettext('Choose a canned response...'))] ]] responses = CannedResponse.objects.filter(type=self.type) # Loop through the actions (public, etc). for k, action in self.helper.actions.iteritems(): action_choices = [[c.response, c.name] for c in responses if c.sort_group and k in c.sort_group.split(',')] # Add the group of responses to the canned_choices array. if action_choices: canned_choices.append([action['label'], action_choices]) # Now, add everything not in a group. for r in responses: if not r.sort_group: canned_choices.append([r.response, r.name]) self.fields['canned_response'].choices = canned_choices self.fields['action'].choices = [ (k, v['label']) for k, v in self.helper.actions.items() ] @property def unreviewed_files(self): return (self.helper.version.unreviewed_files if self.helper.version else [])
def __init__(self, data=None, queryset=None, prefix=None, strict=None, **kwargs): workspace = kwargs.pop('workspace') super(ContatoAgrupadoPorProcessoFilterSet, self).__init__(data=data, queryset=queryset, prefix=prefix, strict=strict, **kwargs) c1_row1 = to_row([ ('search', 7), ('data', 5), ('importancia', 4), ('status', 4), ('classificacoes', 4), ('topicos', 6), ('assuntos', 6), ]) col1 = Fieldset( _('Informações para Seleção de Processos'), c1_row1, to_row([(SubmitFilterPrint('filter', value=_('Filtrar'), css_class='btn-default pull-right', type='submit'), 12)])) col2 = Fieldset( _('Inf p/ Impressão'), 'agrupamento', SubmitFilterPrint('print', value=_('Imprimir'), css_class='btn-primary pull-right', type='submit')) rows = to_row([ (col1, 9), (col2, 3), ]) self.form.helper = FormHelper() self.form.helper.form_method = 'GET' self.form.helper.layout = Layout(rows, ) self.form.fields['search'].label = _('Filtrar Títulos de Processos') self.form.fields['topicos'].widget = forms.SelectMultiple( attrs={'size': '7'}) self.form.fields['topicos'].queryset = TopicoProcesso.objects.all() self.form.fields['assuntos'].widget = forms.SelectMultiple( attrs={'size': '7'}) self.form.fields['assuntos'].queryset = AssuntoProcesso.objects.filter( workspace=workspace) self.form.fields['importancia'].widget = forms.CheckboxSelectMultiple() #self.form.fields['importancia'].inline_class = True self.form.fields[ 'classificacoes'].widget = forms.CheckboxSelectMultiple() self.form.fields['status'].widget = forms.CheckboxSelectMultiple() #self.form.fields['status'].inline_class = True self.form.fields['status'].choices = list( self.form.fields['status'].choices) del self.form.fields['status'].choices[0] self.form.fields['agrupamento'].label = _('Agrupar Contatos') self.form.fields['agrupamento'].widget = forms.RadioSelect()
class MentorForm(forms.ModelForm): class Meta: model = Mentor fields = ['type', 'url', 'picture', 'about', 'expertise', 'phone', 'website', 'facebook', 'twitter', 'googlePlus', 'linkedIn'] type = forms.ChoiceField( choices=MENTOR_TYPE_CHOICES, ) url = forms.URLField( label=_('Directory of ETS'), required=False, ) url.widget.attrs.update({'placeholder': _(u'https://example.com')}) facebook = forms.URLField( label=_('Facebook'), required=False, ) facebook.widget.attrs.update({'placeholder': _(u'https://www.facebook.com/lastname.firstname')}) twitter = forms.URLField( label=_('Twitter'), required=False, ) twitter.widget.attrs.update({'placeholder': _(u'https://twitter.com/username')}) googlePlus = forms.URLField( label=_('Google+'), required=False, ) googlePlus.widget.attrs.update({'placeholder': _(u'https://plus.google.com/id')}) linkedIn = forms.URLField( label=_('linkedIn'), required=False, ) linkedIn.widget.attrs.update({'placeholder': _(u'https://ca.linkedin.com/in/username')}) phone = forms.CharField( label=_('Phone number'), required=False, max_length=10 ) phone.widget.attrs.update({'placeholder': _(u'Phone number')}) website = forms.URLField( label=_('Web site'), required=False, ) website.widget.attrs.update({'placeholder': _(u'https://example.com')}) about = forms.CharField( label=_('Description'), required=False, widget=forms.Textarea( attrs={ 'placeholder': _(u'Write here a brief summary of your skills and your career.'), 'class': 'md-editor' } ) ) expertise = forms.ModelMultipleChoiceField( label=_(u"Areas of expertise"), queryset=Expertise.objects.all(), required=False, widget=forms.SelectMultiple() ) picture = forms.ImageField( label=_('Picture'), required=False, )
class SelectmultipleForm(forms.Form): test_field = forms.MultipleChoiceField( choices=(('V', 'Visa'), ('M', 'MasterCard'), ('P', 'Paypal')), widget=forms.SelectMultiple(attrs={'data-test': 'Test Attr'})) data_field = forms.BooleanField(required=False, widget=forms.HiddenInput, initial=True, help_text='To produce non empty POST for empty test_field')
class ImportarExcelForm(forms.Form): archivo = forms.FileField(label='Subir archivo Excel (.xlsx)') puntocontrol = forms.Field(label='Puntos de Control', widget=forms.SelectMultiple())
class Meta: model = News fields = ( 'url', 'title', 'headline', 'explanation', 'publication_date', 'tags', 'image', 'source', 'country', # 'usuario', ) widgets = { 'url': forms.URLInput( attrs={ 'class': 'form-control', 'required': 'required', 'placeholder': 'https://' }), 'title': forms.TextInput(attrs={ 'class': 'form-control', 'required': 'required' }), 'headline': forms.Textarea(attrs={ 'class': 'form-control', 'rows': 3, 'required': 'required' }), 'explanation': forms.Textarea(attrs={ 'class': 'form-control', 'rows': 20, 'required': 'required' }), 'publication_date': forms.DateInput(format=('%d/%m/%Y'), attrs={ 'class': 'form-control', 'type': 'date', 'required': 'required' }), 'tags': forms.SelectMultiple(attrs={ 'class': 'form-control', 'required': 'required' }), 'image': forms.ClearableFileInput(attrs={ 'class': 'form-control-file', 'required': 'required' }), 'source': forms.Select(attrs={ 'class': 'form-control', 'required': 'required' }), 'country': forms.Select(attrs={ 'class': 'form-control', 'required': 'required' }), }
class Meta: model = Asset fields = [ 'hostname', 'ip', 'port', 'nodes', 'is_active', 'platform', 'public_ip', 'number', 'comment', 'admin_user', 'labels', 'domain', 'protocol', ] widgets = { 'nodes': forms.SelectMultiple(attrs={ 'class': 'select2', 'data-placeholder': _('Node') }), 'admin_user': forms.Select(attrs={ 'class': 'select2', 'data-placeholder': _('Admin user') }), 'labels': forms.SelectMultiple(attrs={ 'class': 'select2', 'data-placeholder': _('Label') }), 'port': forms.TextInput(), 'domain': forms.Select(attrs={ 'class': 'select2', 'data-placeholder': _('Domain') }), } labels = { 'nodes': _("Node"), } help_texts = { 'hostname': '* required', 'ip': '* required', 'port': '* required', 'cluster': '* required', 'admin_user': _('root or other NOPASSWD sudo privilege user existed in asset,' 'If asset is windows or other set any one, more see admin user left menu' ), 'platform': _("* required Must set exact system platform, Windows, Linux ..."), 'domain': _("If your have some network not connect with each other, you can set domain" ) }
class HelloForm(forms.Form): data = [('one', 'item 1'), ('two', 'item 2'), ('three', 'item 3'), ('four', 'item 4'), ('five', 'item 5')] choice = forms.MultipleChoiceField(label='radio',\ choices=data, widget=forms.SelectMultiple(attrs={'size':6}))
class Meta: model = models.Organization fields = ['people'] widgets = { 'people': forms.SelectMultiple(attrs={'size': 15}) }
class DocumentoForm(ModelForm): parlamentares = ModelMultipleChoiceField( queryset=Parlamentar.objects.all(), required=False, label=Parlamentar._meta.verbose_name_plural, widget=forms.SelectMultiple(attrs={'size': '10'}) ) public_date = forms.DateTimeField( widget=forms.HiddenInput(), required=False,) tipo = forms.ChoiceField(choices=Documento.tipo_parte_doc['documentos']) capa = forms.TypedChoiceField(label=_('Capa de sua Classe'), choices=YES_NO_CHOICES, coerce=lambda x: x == 'True') class Meta: model = Documento fields = ['titulo', 'template_doc', 'descricao', 'visibilidade', 'parlamentares', 'public_date', 'tipo', 'listar', 'capa' ] def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.layout = SaplFormLayout( to_row([ ('titulo', 7), ('visibilidade', 3), ('listar', 2) ]), to_row([ ('tipo', 4), ('template_doc', 4), ('capa', 4), ]), to_row([ ('descricao', 8), ('parlamentares', 4) ]), ) super(DocumentoForm, self).__init__(*args, **kwargs) self.fields['parlamentares'].choices = [ ('0', '--------------')] + list( self.fields['parlamentares'].choices) self.fields['capa'].initial = self.instance == self.instance.classe.capa def save(self, commit=True): inst = self.instance if inst.visibilidade != Documento.STATUS_PUBLIC: inst.public_date = None inst.public_end_date = None else: if not inst.public_date: inst.public_date = timezone.now() inst = super().save(commit) if not inst.childs.exists(): container = Documento() container.titulo = '' container.descricao = '' container.classe = inst.classe container.tipo = Documento.TPD_CONTAINER_SIMPLES container.owner = inst.owner container.parent = inst container.ordem = 1 container.visibilidade = inst.visibilidade container.save() classe = inst.classe classe.capa = inst if self.cleaned_data['capa'] else None classe.save() return inst
class AdvancedSearch(forms.Form): target = forms.ChoiceField(choices=[['publisher', 'Publishers'], ['series', 'Series'], ['issue', 'Issues'], ['sequence', 'Stories']], initial='sequence', label='Search For') method_help = "All methods case-insensitive." method = forms.ChoiceField(choices=[['iexact', 'Matches Exactly'], ['istartswith', 'Starts With'], ['icontains', 'Contains']], initial='icontains', label='Search Method', help_text=method_help) logic_help = "This option applies primarily to the story credit fields." \ "It will eventually be replaced by more powerful options." logic = forms.ChoiceField(choices=[[False, 'AND all fields'], [True, 'OR credit, AND other fields']], initial=False, label='Behavior', help_text=logic_help) order1 = forms.ChoiceField(choices=ORDERINGS, required=False, initial='series', label='First By') order2 = forms.ChoiceField(choices=ORDERINGS, required=False, initial='date', label='Second By') order3 = forms.ChoiceField(choices=ORDERINGS, required=False, label='Third By') start_date = forms.DateField(label='Start Date', required=False, input_formats=DATE_FORMATS) end_date = forms.DateField(label='End Date', required=False, input_formats=DATE_FORMATS) pub_name = forms.CharField(label='Publisher', required=False) pub_notes = forms.CharField(label='Notes', required=False) series = forms.CharField(label='Name', required=False) format = forms.CharField(label='Format', required=False) series_notes = forms.CharField(label='Series Notes', required=False) tracking_notes = forms.CharField(label='Tracking Notes', required=False) publication_notes = forms.CharField(label='Publication Notes', required=False) issues = forms.CharField(label='Issues', required=False) # Volume is a char field to allow ranges and lists. volume = forms.CharField(label='Volume', required=False) brand = forms.CharField(required=False) indicia_publisher = forms.CharField(label='Indicia Publisher', required=False) price = forms.CharField(required=False) issue_pages = forms.CharField(required=False) issue_notes = forms.CharField(label='Issue Notes', required=False) issue_editing = forms.CharField(required=False) issue_date = forms.CharField(label='Cover Date', required=False) cover_needed = forms.BooleanField(label="Cover is Needed", required=False) has_stories = forms.NullBooleanField( label="Has Stories", required=False, widget=forms.Select(choices=((None, ""), (True, "yes"), (False, "no")))) indexer = forms.ModelMultipleChoiceField( required=False, queryset=Indexer.objects.filter(registration_key=None).order_by( 'user__first_name', 'user__last_name').select_related('user'), widget=forms.SelectMultiple(attrs={'size': '6'})) feature = forms.CharField(required=False) type = forms.ModelMultipleChoiceField( queryset=StoryType.objects.all(), widget=forms.SelectMultiple(attrs={'size': '6'}), required=False) title = forms.CharField(required=False) pages = forms.CharField(required=False) script = forms.CharField(required=False) pencils = forms.CharField(required=False) inks = forms.CharField(required=False) colors = forms.CharField(required=False) letters = forms.CharField(required=False) story_editing = forms.CharField(required=False) job_number = forms.CharField(label='Job Number', required=False) genre = forms.CharField(required=False) characters = forms.CharField(required=False) synopsis = forms.CharField(required=False) reprint_notes = forms.CharField(required=False) notes = forms.CharField(label='Notes', required=False) country = forms.MultipleChoiceField( required=False, choices=([c.code, c.name.title()] for c in Country.objects.order_by('name')), widget=forms.SelectMultiple(attrs={'size': '4'})) alt_country = forms.CharField(label='', required=False, max_length=3) language = forms.MultipleChoiceField( required=False, choices=([l.code, l.name] for l in Language.objects.order_by('name')), widget=forms.SelectMultiple(attrs={'size': '4'})) alt_language = forms.CharField(label='', required=False, max_length=3) def clean_pages(self): pages_data = self.cleaned_data['pages'] if pages_data: range_match = match(PAGE_RANGE_REGEXP, pages_data) if not range_match: try: Decimal(pages_data) except InvalidOperation: raise forms.ValidationError( "Page count must be a decimal number or a pair of " "decimal numbers separated by a hyphen.") return pages_data def clean_issue_pages(self): pages_data = self.cleaned_data['issue_pages'] if pages_data: range_match = match(PAGE_RANGE_REGEXP, pages_data) if not range_match: try: Decimal(pages_data) except InvalidOperation: raise forms.ValidationError( "Page count must be a decimal number or a pair of " "decimal numbers separated by a hyphen.") return pages_data def clean(self): cleaned_data = self.cleaned_data if cleaned_data['cover_needed']: # use of in since after distinction stuff is cleared add series if cleaned_data['target'] not in ['issue', 'series']: raise forms.ValidationError( "Searching for covers which are missing or need to be" " replaced is valid only for issue or series searches.") return cleaned_data
class KeywordSearchForm(forms.Form): kwd = forms.ModelChoiceField( queryset=Keyword.objects.all().order_by('name'), widget=forms.SelectMultiple(attrs={'size': '15'}), empty_label=None)
class ReachForm(forms.Form): dagrs = Dagr.objects.all() dagr_id = forms.ModelMultipleChoiceField(queryset=dagrs,label="Choose DAGR ID",required=True, widget=forms.SelectMultiple(attrs={'class':'form-control'})) ancestors = forms.IntegerField(label="Choose Depth Ancestors", required=False, widget=forms.TextInput(attrs={'class':'form-control'})) descendants = forms.IntegerField(label="Choose Depth Descendants", required=False, widget=forms.TextInput(attrs={'class':'form-control'}))
class CladeGroupForm(forms.Form): clade_group = forms.CharField(widget=forms.SelectMultiple( {'class': 'form-control multiselect clade-group-select'}), required=False)
class Meta: model = Advertise_with_Us fields = [ 'Business_Name', 'Business_Category', 'Business_Subcategory', 'Business_Services', 'Business_Telephone', 'Business_WhatsApp', 'Business_Address', 'Business_Location', 'Business_Email', 'Business_Website', 'Business_Facebook', 'Business_Instagram', 'Business_Twitter', 'Business_Linkedin', 'Business_Pinterest', 'Business_Github', 'Business_Description', 'tags', 'Business_Logo', 'Business_Images', 'Business_Established_Date', 'Mode_Of_Payments', ] widgets = { 'Business_Name': forms.TextInput( attrs={'placeholder': 'Enter Your Business Name Here...'}), 'Business_Location': forms.TextInput( attrs={'placeholder': 'Enter Your Business Address Here...'}), 'Business_Category': forms.Select(attrs={'class': 'chosen-select'}), 'Business_Subcategory': forms.SelectMultiple(attrs={ 'id': 'my-select', }), 'Business_Services': forms.SelectMultiple(attrs={'id': 'service-select'}), 'Business_Website': forms.URLInput( attrs={'placeholder': 'Enter Your Business Website Here...'}), 'Business_Facebook': forms.URLInput( attrs={'placeholder': 'Enter Your Facebook Page Here...'}), 'Business_Instagram': forms.URLInput( attrs={'placeholder': 'Enter Your Instagram Page Here...'}), 'Business_Twitter': forms.URLInput( attrs={'placeholder': 'Enter Your Twitter Handle Here...'}), 'Business_Linkedin': forms.URLInput( attrs={'placeholder': 'Enter Your Linkedin Page Here...'}), 'Business_Pinterest': forms.URLInput( attrs={'placeholder': 'Enter Your Pinterest Board Here...'}), 'Business_Github': forms.URLInput( attrs={'placeholder': 'Enter Your Github Profile Here...'}), 'Business_Email': forms.EmailInput( attrs={'placeholder': 'Enter Your Business Email Here...'}), 'Business_Description': forms.Textarea( attrs={'placeholder': 'Describe Your Business Here...'}), 'Business_Images': forms.ClearableFileInput(attrs={'class': 'form-control'}), 'Business_Logo': forms.FileInput(attrs={'class': 'form-control'}), 'Business_Established_Date': DateInput(attrs={'class': 'form-control'}), 'Mode_Of_Payments': forms.CheckboxSelectMultiple }
class SearchForm(forms.Form): semfield = forms.ModelMultipleChoiceField(queryset=SemanticField.objects.all().order_by('field'),required=False, label='Семантическое поле', widget=forms.SelectMultiple(attrs={'multiple class':'form-control', 'size': 'big'})) meaning_type = forms.ModelMultipleChoiceField(queryset=MeaningType.objects.all(),required=False, widget=forms.CheckboxSelectMultiple(attrs={'class': 'form-check-input'}), label='Тип значения') meaning_choices = Meaning.objects.order_by('meaning').values_list('meaning',flat=True).distinct() meaning = forms.MultipleChoiceField(choices=zip(meaning_choices,meaning_choices),required=False, label='Значение', widget=forms.SelectMultiple(attrs={'multiple class':'form-control', 'size': 'big'})) object_ref = forms.MultipleChoiceField(choices=OBJECT_REF_CHOICES,required=False,widget=forms.CheckboxSelectMultiple(attrs={'class': 'form-check-input'}), label='Референтность объекта') object_animacy = forms.MultipleChoiceField(choices=OBJECT_ANIMACY_CHOICES,required=False,widget=forms.CheckboxSelectMultiple(attrs={'class': 'form-check-input'}), label='Одушевлённость объекта') purpose = forms.MultipleChoiceField(choices=PURPOSE_CHOICES,required=False,widget=forms.CheckboxSelectMultiple(attrs={'class': 'form-check-input'}), label='Намерение') language = forms.ModelMultipleChoiceField(queryset=Language.objects.all().order_by('language'),required=False, label='Язык', widget=forms.SelectMultiple(attrs={'multiple class':'form-control', 'size': 'md'})) verb_conj = forms.ChoiceField(choices=[('and','AND'),('or','OR')], widget=forms.RadioSelect(attrs={'class': 'form-check-label'}), label='Отношение между несколькими выбранными глаголами') verb = forms.ModelMultipleChoiceField(queryset=Verb.objects.all().order_by('language__language','verb'),required=False, label='Глагол', widget=forms.SelectMultiple(attrs={'class':'form-control', 'size': 'big'})) example = forms.CharField(max_length=300,required=False, label='Пример', widget=forms.Textarea(attrs={'class':'form-control', 'rows':1}))