def test_multiplechoicefield_changed(self): f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two'), ('3', 'Three')]) self.assertFalse(f.has_changed(None, None)) self.assertFalse(f.has_changed([], None)) self.assertTrue(f.has_changed(None, ['1'])) self.assertFalse(f.has_changed([1, 2], ['1', '2'])) self.assertFalse(f.has_changed([2, 1], ['1', '2'])) self.assertTrue(f.has_changed([1, 2], ['1'])) self.assertTrue(f.has_changed([1, 2], ['1', '3']))
class PreSelectedModelSearchForm(ModelSearchForm): possible_facets = MultipleChoiceField(widget=CheckboxSelectMultiple, choices=(), required=False, label=_("Finding facets on")) search_type = ChoiceField(choices=[(0, "Autoquery"), (1, "Exact")], required=False, initial=0, label=_("Search type")) content_field = ChoiceField(choices=(), required=False, label=_("Indexed fields")) connection = ChoiceField(choices=(), required=False) p = IntegerField(required=False, label=_("Page"), min_value=0, max_value=99999999, initial=1) def __init__(self, *args, **kwargs): """ If we're in a recognised faceting engine, display and allow faceting. """ super(PreSelectedModelSearchForm, self).__init__(*args, **kwargs) if 'models' in self.fields: self.fields['models'].initial = [x[0] for x in model_choices()] self.fields['models'].label = _("Only models") self.haystack_config = HaystackConfig() self.fields['content_field'].choices = content_field_choices() self.version = self.haystack_config.version if self.should_allow_faceting(): possible_facets = self.configure_faceting() self.fields['possible_facets'].choices = possible_facets self.fields['selected_facets'] = SelectedFacetsField( choices=(), required=False, possible_facets=possible_facets) if self.has_multiple_connections(): wtf = self.get_possible_connections() self.fields['connection'].choices = tuple(wtf) # noqa self.fields['connection'].initial = 'default' else: self.fields['connection'].widget = HiddenInput() def is_haystack1(self): return self.haystack_config.is_version_1x() def is_haystack2(self): return self.haystack_config.is_version_2x() def guess_haystack_version(self): return self.haystack_config.version def has_multiple_connections(self): return self.haystack_config.has_multiple_connections() def get_possible_connections(self): return self.haystack_config.get_connections() def configure_faceting(self): possible_facets = self.haystack_config.get_facets( sqs=self.searchqueryset) return [Facet(x).choices() for x in sorted(possible_facets)] def should_allow_faceting(self): return self.haystack_config.supports_faceting() def __repr__(self): is_valid = self.is_bound and not bool(self._errors) return '<%(module)s.%(cls)s bound=%(is_bound)s valid=%(valid)s ' \ 'version=%(version)d multiple_connections=%(conns)s ' \ 'supports_faceting=%(facets)s>' % { 'module': self.__class__.__module__, 'cls': self.__class__.__name__, 'is_bound': yesno(self.is_bound), 'conns': yesno(self.has_multiple_connections()), 'facets': yesno(self.should_allow_faceting()), 'valid': yesno(is_valid), 'version': self.haystack_config.version, } def no_query_found(self): """ When nothing is entered, show everything, because it's a better useful default for our usage. """ return self.searchqueryset.all() def search(self): sqs = self.searchqueryset.all() if not self.is_valid(): # When nothing is entered, show everything, because it's a better # useful default for our usage. return sqs cleaned_data = getattr(self, 'cleaned_data', {}) connection = cleaned_data.get('connection', ()) if self.has_multiple_connections() and len(connection) == 1: sqs = sqs.using(*connection) if self.should_allow_faceting(): for applied_facet in self.applied_facets(): narrow_query = applied_facet.narrow.format( cleaned_value=sqs.query.clean(applied_facet.value)) sqs = sqs.narrow(narrow_query) to_facet_on = sorted(cleaned_data.get('possible_facets', ())) if len(to_facet_on) > 0: for field in to_facet_on: sqs = sqs.facet(field) only_models = self.get_models() if len(only_models) > 0: sqs = sqs.models(*only_models) content_field = cleaned_data.get('content_field', ['content']) query = cleaned_data.get('q', None) if query and query[0]: if cleaned_data.get("search_type", 0) == "1": kwargs = {content_field[0]: Exact(*query)} sqs = sqs.filter(**kwargs) else: sqs = sqs.auto_query(*query, fieldname=content_field[0]) if self.load_all: sqs = sqs.load_all() return sqs def clean_connection(self): return [self.cleaned_data.get('connection', 'default').strip()] def clean_possible_facets(self): return list(frozenset(self.cleaned_data.get('possible_facets', ()))) def clean_selected_facets(self): return list(frozenset(self.cleaned_data.get('selected_facets', ()))) def clean_q(self): return [self.cleaned_data.get('q', '')] def clean_content_field(self): return [self.cleaned_data.get('content_field', '')] def clean_p(self): page = self.cleaned_data.get('p', None) if page is None: page = self.fields['p'].min_value return [page] def full_clean(self): """ Taken from Django master as of 5e06fa1469180909c51c07151692412269e51ea3 but is mostly a copy-paste all the way back to 1.3.1 Basically we want to keep cleaned_data around, not remove it if errors occured. """ self._errors = ErrorDict() if not self.is_bound: # Stop further processing. return self.cleaned_data = {} # If the form is permitted to be empty, and none of the form data has # changed from the initial data, short circuit any validation. if self.empty_permitted and not self.has_changed(): return self._clean_fields() self._clean_form() self._post_clean() def clean(self): cd = self.cleaned_data selected = 'selected_facets' possible = 'possible_facets' if selected in cd and len(cd[selected]) > 0: if possible not in cd or len(cd[possible]) == 0: raise ValidationError( 'Unable to provide facet counts without selecting a field to facet on' ) return cd def applied_facets(self): cleaned_querydict = self.cleaned_data_querydict return AppliedFacets(querydict=cleaned_querydict) @property def cleaned_data_querydict(self): """ Creates an immutable QueryDict instance from the form's cleaned_data """ query = QueryDict('', mutable=True) # make sure cleaned_data is available, if possible ... self.is_valid() cleaned_data = getattr(self, 'cleaned_data', {}) for key, values in cleaned_data.items(): query.setlist(key=key, list_=values) query._mutable = False return query
def check_for_widget(self, widget, field): if widget: for field_to_set_widget, widget in widget.items(): if field_to_set_widget == field: return (True, widget, MultipleChoiceField().__class__)
def test_disabled_has_changed(self): f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')], disabled=True) self.assertIs(f.has_changed('x', 'y'), False)
def test_multiplechoicefield_3(self): f = MultipleChoiceField( choices=[('Numbers', (('1', 'One'), ('2', 'Two'))), ('Letters', (('3', 'A'), ('4', 'B'))), ('5', 'Other')] ) self.assertEqual(['1'], f.clean([1])) self.assertEqual(['1'], f.clean(['1'])) self.assertEqual(['1', '5'], f.clean([1, 5])) self.assertEqual(['1', '5'], f.clean([1, '5'])) self.assertEqual(['1', '5'], f.clean(['1', 5])) self.assertEqual(['1', '5'], f.clean(['1', '5'])) msg = "'Select a valid choice. 6 is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): f.clean(['6']) msg = "'Select a valid choice. 6 is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): f.clean(['1', '6'])
class ButtonMenuEditForm(CremeForm): # TODO: use EnhancedMultipleChoiceField + description of the button as help text ? button_ids = MultipleChoiceField( label=_('Buttons to display'), required=False, choices=(), widget=ButtonMenuEditionWidget, help_text=_("Drag and drop the buttons between the available buttons and " "the selected buttons sections to enable or disable the buttons, " "or within the selected buttons section to change the order.") ) def __init__(self, button_menu_items, ct_id, button_registry=None, *args, **kwargs): super().__init__(*args, **kwargs) self.ct = ContentType.objects.get_for_id(ct_id) if ct_id else None self.set_buttons = button_menu_items button_registry = button_registry or button_menu.button_registry choices = [] if not self.ct: # Default conf choices.extend( (id_, button) for id_, button in button_registry if not button.get_ctypes() ) else: model_class = self.ct.model_class() default_conf_ids = frozenset( ButtonMenuItem.objects .filter(content_type=None) .values_list('button_id', flat=True) ) for id_, button in button_registry: ctypes = button.get_ctypes() if not ctypes: if id_ not in default_conf_ids: choices.append((id_, button)) elif model_class in ctypes: choices.append((id_, button)) sort_key = collator.sort_key choices.sort(key=lambda c: sort_key(str(c[1].verbose_name))) button_ids = self.fields['button_ids'] button_ids.choices = choices button_ids.initial = [bmi.button_id for bmi in button_menu_items] def save(self): button_ids = self.cleaned_data['button_ids'] ct = self.ct BMI_objects = ButtonMenuItem.objects BMI_get = BMI_objects.get if not button_ids: # No pk to BMI objects --> can delete() on queryset directly BMI_objects.filter(content_type=ct).delete() # No button for this content type -> fake button_id ButtonMenuItem.objects.create(content_type=ct, button_id='', order=1) else: old_ids = {bmi.button_id for bmi in self.set_buttons} new_ids = {*button_ids} buttons_2_del = old_ids - new_ids buttons_2_add = new_ids - old_ids # No pk to BCI objects --> can delete() on queryset directly BMI_objects.filter(content_type=ct, button_id__in=buttons_2_del).delete() offset = 1 if ct is None else 1000 # Default conf before ct's conf for i, button_id in enumerate(button_ids): if button_id in buttons_2_add: ButtonMenuItem.objects.create( content_type=ct, button_id=button_id, order=i + offset, ) else: bmi = BMI_get(content_type=ct, button_id=button_id) if bmi.order != i + offset: bmi.order = i + offset bmi.save()
class BulkCopyIndicatorsForm(forms.Form): destination_domain = forms.CharField(label="Destination Project Space") indicator_ids = MultipleChoiceField( label="Indicator(s)", validators=[MinLengthValidator(1)]) def __init__(self, domain=None, couch_user=None, indicator_class=None, *args, **kwargs): super(BulkCopyIndicatorsForm, self).__init__(*args, **kwargs) self.domain = domain self.couch_user = couch_user self.indicator_class = indicator_class self.fields['destination_domain'].widget = forms.Select(choices=[(d, d) for d in self.available_domains]) self.fields['indicator_ids'].choices = self.available_indicators self.helper = FormHelper() self.helper.label_class = 'col-sm-3' self.helper.field_class = 'col-sm-9' @property @memoized def available_domains(self): if not self.couch_user: return [] indicator_domains = set(get_indicator_domains()) indicator_domains = indicator_domains.difference([self.domain]) return [d for d in indicator_domains if self.couch_user.has_permission(d, Permissions.edit_data)] @property @memoized def available_indicators(self): indicators = [] for namespace in get_namespaces(self.domain): indicators.extend(self.indicator_class.get_all_of_type(namespace, self.domain)) return [(i._id, "%s | v. %d | n: %s" % (i.slug, i.version if i.version else 0, get_namespace_name(i.domain, i.namespace))) for i in indicators] def clean_destination_domain(self): if 'destination_domain' in self.cleaned_data: destination = self.cleaned_data['destination_domain'] if not self.couch_user or not self.couch_user.has_permission(destination, Permissions.edit_data): raise ValidationError("You do not have permission to copy indicators to this project space.") if destination not in self.available_domains: raise ValidationError("You submitted an invalid destination project space") return destination def copy_indicators(self): failed = [] success = [] destination_domain = self.cleaned_data['destination_domain'] available_namespaces = get_namespaces(destination_domain) indicator_ids = self.cleaned_data['indicator_ids'] for indicator_id in indicator_ids: try: indicator = self.indicator_class.get(indicator_id) properties_to_exclude = [ 'last_modified', 'base_doc', 'namespace', 'domain', 'class_path', 'version' ] if indicator.namespace not in available_namespaces: failed.append(dict(indicator=indicator.slug, reason='Indicator namespace not available for destination project.')) continue properties = set(indicator.properties().keys()) copied_properties = properties.difference(properties_to_exclude) copied_properties = dict([(p, getattr(indicator, p)) for p in copied_properties]) copied_indicator = self.indicator_class.increment_or_create_unique( indicator.namespace, destination_domain, **copied_properties ) if copied_indicator: success.append(copied_indicator.slug) except Exception as e: failed.append(dict(indicator=indicator_id, reason='Could not retrieve indicator %s due to error %s:' % (indicator_id, e))) return { 'success': success, 'failure': failed, }
def __init__(self, *args, **kwargs): self.question = kwargs.pop("question", None) self.department = kwargs.pop("department", None) self.survey = kwargs.pop("survey", None) super().__init__(*args, **kwargs) options = [(o.id, o.text) for o in self.question.options()] self.field_name = f"option" self.option_field = False if self.question.qtype == "MULTICHOICE": self.single = False self.option_field = True self.fields[self.field_name] = MultipleChoiceField( label=self.question.text, choices=options, widget=forms.CheckboxSelectMultiple(), required=False, ) elif self.question.qtype == "SINGLECHOICE": self.single = True self.option_field = True self.fields[self.field_name] = ChoiceField( label=self.question.text, choices=options, widget=forms.RadioSelect(), required=False, ) elif self.question.qtype == "SELECT": self.single = True self.option_field = True self.fields[self.field_name] = ChoiceField( label=self.question.text, choices=options, required=False, ) elif self.question.qtype == "TEXT": self.single = True self.fields[self.field_name] = CharField( label=self.question.text, required=False, ) elif self.question.qtype == "ESSAY": self.single = True self.fields[self.field_name] = CharField( label=self.question.text, widget=forms.Textarea, required=False, ) elif self.question.qtype == "INTEGER": self.single = True self.fields[self.field_name] = IntegerField( label=self.question.text, required=False, ) elif self.question.qtype == "EMAIL": self.single = True self.fields[self.field_name] = EmailField( label=self.question.text, required=False, ) else: raise AttributeError("Bad field type") self.fields["qid"] = forms.CharField( label="qid", max_length=10, widget=forms.HiddenInput() ) self.fields[self.field_name].help_text = self.question.help_text
class SearchForm(Form): q = CharField(initial='', widget=TextInput( attrs={ 'id': 'search', 'class': 'form-control', 'autofocus': True, 'placeholder': "Search in record and full text" })) type = MultipleChoiceField(choices=defs.DOC_TYPE) tr_type_of_document = MultipleChoiceField() tr_field_of_application = MultipleChoiceField() tr_status = MultipleChoiceField() tr_place_of_adoption = MultipleChoiceField() tr_depository = MultipleChoiceField() dec_type_of_document = MultipleChoiceField() dec_status = MultipleChoiceField() dec_treaty_name = MultipleChoiceField() cd_type_of_document = MultipleChoiceField() cd_territorial_subdivision = MultipleChoiceField() lit_type_of_text = MultipleChoiceField() lit_author = MultipleChoiceField() lit_orig_serial_title = MultipleChoiceField() lit_publisher = MultipleChoiceField() leg_type_of_document = MultipleChoiceField() leg_territorial_subdivision = MultipleChoiceField() leg_status = MultipleChoiceField() xsubjects = MultipleChoiceField() xkeywords = MultipleChoiceField() xcountry = MultipleChoiceField() xregion = MultipleChoiceField() xlanguage = MultipleChoiceField() yearmin = CharField() yearmax = CharField() sortby = CharField(initial='') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # add AND-able fields for f in defs._AND_OP_FACETS: fname = self.get_and_field_name_for(f) self.fields[fname] = BooleanField() # no field is required for field in self.fields.values(): field.required = False @staticmethod def get_and_field_name_for(field): return defs._AND_OP_FIELD_PATTERN % field def _has_document_type(self, doctype): return doctype in self.data.get('type', []) def has_treaty(self): return self._has_document_type('treaty') def has_decision(self): return self._has_document_type('decision') def has_literature(self): return self._has_document_type('literature') def has_legislation(self): return self._has_document_type('legislation') def has_court_decision(self): return self._has_document_type('court_decision')
class _ExampleForm(Form): single = ChoiceField(choices=((1, "one"), (2, "two"), (3, "three")), required=False) multi = MultipleChoiceField( choices=((1, "one"), (2, "two"), (3, "three"), (4, "four"), (5, "five")), required=False, )
threshold = ChoiceField(choices=[(25,25),(90,90)], required=False) resolutionMin = FloatField(required=False, min_value=0, initial=0, widget=TextInput(attrs={'size':3})) resolutionMax = FloatField(required=False, min_value=0, initial=1.2, widget=TextInput(attrs={'size':3})) rfactorMin = FloatField(required=False, min_value=0, initial=0, widget=TextInput(attrs={'size':3})) rfactorMax = FloatField(required=False, min_value=0, initial=0.25, widget=TextInput(attrs={'size':3})) rfreeMin = FloatField(required=False, min_value=0, initial=0, widget=TextInput(attrs={'size':3})) rfreeMax = FloatField(required=False, min_value=0, initial=0.30, widget=TextInput(attrs={'size':3})) proteins = CharField(required=False) proteins_i = IntegerField(required=False, widget=HiddenInput(attrs={'class':'include'})) residues = ChoiceField(choices=[(i,i) for i in range(1, settings.SEGMENT_SIZE+1)], initial=3) # Build a dict for the fields of variable number form_dict = {'__module__' : 'pgd_search.views'} for i in RESIDUE_INDEXES: form_dict["aa_%i" % i] = MultipleChoiceField(choices=AA_CHOICES, required=False, widget=SelectMultiple(attrs={'class':'field'})) form_dict["aa_i_%i" % i] = IntegerField(required=False, widget=HiddenInput(attrs={'class':'include'})) form_dict["ss_%i" % i] = MultipleChoiceField(choices=SS_CHOICES, required=False, widget=SelectMultiple(attrs={'class':'field'})) form_dict["ss_i_%i" % i] = IntegerField(required=False, widget=HiddenInput(attrs={'class':'include'})) # the loops here are just to save on space/typing for j in range(1,8): # Angles form_dict["a%i_%i" % (j,i)] = SearchSyntaxField(required=False, widget=TextInput(attrs={'class':'field needs_reset', 'size':8})) form_dict["a%i_i_%i" % (j,i)] = IntegerField(required=False, widget=HiddenInput(attrs={'class':'include'})) for j in range(1,6): # Lengths form_dict["L%i_%i" % (j, i)] = SearchSyntaxField(required=False, widget=TextInput(attrs={'class':'field needs_reset', 'size':8})) form_dict["L%i_i_%i" % (j, i)] = IntegerField(required=False, widget=HiddenInput(attrs={'class':'include'})) for j in ("phi", "psi", "ome", "chi1","chi2","chi3","chi4",'chi5', "bm", "bs", "bg", "h_bond_energy", "zeta"): form_dict["%s_%i" % (j, i)] = SearchSyntaxField(required=False, widget=TextInput(attrs={'class':'field needs_reset', 'size':8})) form_dict["%s_i_%i" % (j, i)] = IntegerField(required=False, widget=HiddenInput(attrs={'class':'include'}))
class LogSearchForm(Form): class FormNotValid(StandardError): pass import logging #matrix parameters for call type = MultipleChoiceField(choices=( ('all', 'All'), ('DELETE_LIBRARY', 'DELETE_LIBRARY'), ('UPDATE_LIBRARY_ITEM_METADATA', 'UPDATE_LIBRARY_ITEM_METADATA'), ('NONE', 'NONE'), ('IMPORT', 'IMPORT'), ('TRANSCODE', 'TRANSCODE'), ('RAW_TRANSCODE', 'RAW_TRANSCODE'), ('CONFORM', 'CONFORM'), ('TRANSCODE_RANGE', 'TRANSCODE_RANGE'), ('PLACEHOLDER_IMPORT', 'PLACEHOLDER_IMPORT'), ('RAW_IMPORT', 'RAW_IMPORT'), ('THUMBNAIL', 'THUMBNAIL'), ('AUTO_IMPORT', 'AUTO_IMPORT'), ('EXPORT', 'EXPORT'), ('COPY_FILE', 'COPY_FILE'), ('DELETE_FILE', 'DELETE_FILE'), ('MOVE_FILE', 'MOVE_FILE'), ('ESSENCE_VERSION', 'ESSENCE_VERSION'), ('FCS_RESTORE', 'FCS_RESTORE'), ('TIMELINE', 'TIMELINE'), ('SHAPE_IMPORT', 'SHAPE_IMPORT'), ('LIST_ITEMS', 'LIST_ITEMS'), ('ANALYZE', 'ANALYZE'), ('SHAPE_UPDATE', 'SHAPE_UPDATE'), ('ARCHIVE', 'ARCHIVE'), ('RESTORE', 'RESTORE'), ('SIDECAR_IMPORT', 'SIDECAR_IMPORT'), ('TEST_TRANSFER', 'TEST_TRANSFER'), ), widget=CheckboxSelectMultiple()) state = MultipleChoiceField( choices=( ('all', 'All'), ('NONE', 'None'), ('READY', 'Ready'), ('STARTED', 'Started'), ('STARTED_ASYNCHRONOUS', 'Started Asynchronous'), ('STARTED_PARALLEL', 'Started in background'), ('STARTED_PARALLEL_ASYNCHRONOUS', 'Started in background, asynchronous'), ('STARTED_SUBTASKS', 'Started and doing in multiple subtasks'), ('FINISHED', 'Completed'), ('FAILED_RETRY', 'Retrying'), ('FAILED_FATAL', 'Failed'), ('FAILED_TOTAL', 'Failed'), ('WAITING', 'Waiting'), #see /job/{job-id}/problem ('DISAPPEARED', 'Disappeared, lost worker')), widget=CheckboxSelectMultiple()) sort = ChoiceField(choices=( ('startTime', 'Start Time'), ('priority', 'Priority'), ('jobId', 'Job ID'), ('type', 'Type'), ('state', 'State'), ('user', 'User'), ), widget=Select(attrs={'style': 'width: 98%'})) sortOrder = ChoiceField( choices=( ('desc', 'Descending'), ('asc', 'Ascending'), ), widget=RadioSelect(), ) fromDate = DateField(label="Starting from", widget=TextInput(attrs={'style': 'width: 60%'})) fromTime = TimeField(label="Starting from", widget=TextInput(attrs={'style': 'width: 60%'})) toDate = DateField(label="Ending at", widget=TextInput(attrs={'style': 'width: 60%'})) toTime = TimeField(label="Ending at", widget=TextInput(attrs={'style': 'width: 60%'})) #Query parameters for call jobmetadata = CharField(max_length=32768, widget=Textarea, required=False) #my own params which will be put into the above fileNameContains = CharField( max_length=512, widget=TextInput(attrs={'style': 'width: 98%; visibility: hidden'}), required=False) columns = MultipleChoiceField(choices=( ('jobId', 'jobId'), ('status', 'status'), ('type', 'type'), ('started', 'started'), ('priority', 'priority'), ('itemid', 'itemid'), ('systemJobModule', 'systemJobModule'), ('systemJobInfo', 'systemJobInfo'), ('destinationStorageId', 'destinationStorageId'), ('bestEffortFilename', 'bestEffortFilename'), ('fileId', 'fileId'), ('replicatedFileIds', 'replicatedFileIds'), ('fileDeleted', 'fileDeleted'), ('fileStateOnFailure', 'fileStateOnFailure'), ('filePathMap', 'filePathMap'), ('replicatedFileInfo', 'replicatedFileInfo'), ('checkReplicatedFiles', 'checkReplicatedFiles'), ), widget=CheckboxSelectMultiple()) def vidispine_query_url(self, base, page): from datetime import datetime import time import calendar if not self.is_valid(): raise self.FormNotValid() #logger=self.logging.getLogger("LogSearchForm::vidispine_query_url") d = self.cleaned_data if page == 1: pagesetting = 0 else: pagesetting = page * 100 - 100 pagesettingready = str(pagesetting) matrixparams = "" if not 'all' in d['state']: matrixparams += ";state=" + ",".join( map(lambda x: urllib.quote_plus(x, safe=""), d['state'])) if not 'all' in d['type']: matrixparams += ";type=" + ",".join( map(lambda x: urllib.quote_plus(x, safe=""), d['type'])) matrixparams += ";number=100;first=" + pagesettingready + ";sort={0}%20{1}".format( urllib.quote_plus(d['sort'], safe=""), d['sortOrder']) queryparams = "?metadata=true" if d['fileNameContains']: queryparams += "&jobmetadata=" + urllib.quote_plus( "bestEffortFilename=*{0}*".format(d['fileNameContains']), safe="") if d['jobmetadata']: queryparams += "&jobmetadata=" + urllib.quote_plus( d['jobmetadata'], safe="") fromTime = datetime.combine(d['fromDate'], d['fromTime']) toTime = datetime.combine(d['toDate'], d['toTime']) queryparams += "&starttime-from=" + urllib.quote_plus( fromTime.strftime("%Y-%m-%dT%H:%M:%S.%f"), safe="") queryparams += "&starttime-to=" + urllib.quote_plus( toTime.strftime("%Y-%m-%dT%H:%M:%S.%f"), safe="") print "debug: vidispine_query_url is {0}".format(base + matrixparams + queryparams) return base + matrixparams + queryparams
class IntegrationScaffoldingForm(Form): name = CharField(max_length=80, label=_('Integration name'), widget=TextInput()) author_homepage = URLField(label=_('Author\'s homepage'), required=False) issue_tracker = URLField(label=_('Issue tracker URL'), required=False, help_text=_('Bug reports and feature requests')) categories = MultipleChoiceField(widget=HiddenInput(), disabled=True, required=True, label=_('Categories'), choices=lazy(get_categories, list), help_text=_('Hold down Ctrl and click to ' 'select multiple entries')) summary = CharField( max_length=256, label=_('Summary'), help_text= _('Short description of your app that will be rendered as short teaser' )) screenshot = URLField(max_length=256, label=_('Screenshot URL'), required=False, help_text=_('URL for integration screenshot')) screenshot_thumbnail = URLField(max_length=256, label=_('Screenshot ' 'thumbnail URL'), required=False, help_text=_('URL for integration ' 'screenshot in ' 'smaller dimensions. ' 'Must be used in combination ' 'with a larger screenshot.')) description = CharField(widget=Textarea, label=_('Description'), help_text=_('Full description of what your' ' integration ' 'does. Can contain Markdown.')) def _create_discourse_category(self, app_id: str) -> None: url = '%s/categories?api_key=%s&api_username=%s' % ( settings.DISCOURSE_URL.rstrip('/'), settings.DISCOURSE_TOKEN, settings.DISCOURSE_USER) data = { 'name': app_id.replace('_', '-'), 'color': '3c3945', 'text_color': 'ffffff' } if settings.DISCOURSE_PARENT_CATEGORY_ID: data['parent_category_id'] = settings.DISCOURSE_PARENT_CATEGORY_ID # ignore requests errors because there can be many issues and we do not # want to abort app registration just because the forum is down or # leak sensitive data like tokens or users try: requests.post(url, data=data) except requests.HTTPError: pass def save(self, user, app_id, action): if app_id is None: app_id = slugify(self.cleaned_data['name']).replace('-', '_')[:80] try: app = App.objects.get(id=app_id) if app.can_update(user) or user.is_superuser: if action == "reject" and user.is_superuser: '''Not optimal but works''' Screenshot.objects.filter(app=app).delete() app.delete() elif action == "approve" and user.is_superuser: app.approved = True if settings.DISCOURSE_TOKEN: self._create_discourse_category(app_id) app.save() return app_id else: '''Not optimal but works''' Screenshot.objects.filter(app=app).delete() if self.data['screenshot']: screenshot = Screenshot.objects.create( url=self.cleaned_data['screenshot'], small_thumbnail=self. cleaned_data['screenshot_thumbnail'], ordering=1, app=app) screenshot.save() app.description = self.cleaned_data['description'] app.name = self.cleaned_data['name'] app.summary = self.cleaned_data['summary'] app.website = self.cleaned_data['author_homepage'] app.issue_tracker = self.cleaned_data['issue_tracker'] app.save() return app_id except App.DoesNotExist: app = App.objects.create(id=app_id, owner=user, certificate=uuid.uuid1().urn) app.set_current_language('en') app.categories.set(self.cleaned_data['categories']) app.description = self.cleaned_data['description'] app.name = self.cleaned_data['name'] app.summary = self.cleaned_data['summary'] app.website = self.cleaned_data['author_homepage'] app.issue_tracker = self.cleaned_data['issue_tracker'] app.save() p = App.objects.get(id=app_id) p.is_integration = True if user.is_superuser: p.approved = True if settings.DISCOURSE_TOKEN: self._create_discourse_category(app_id) else: send_mail( "New integration submitted", "Please review the " "integration to make " "sure it fits the " "guidelines.", settings.NEXTCLOUD_FROM_EMAIL, settings.NEXTCLOUD_INTEGRATIONS_APPROVAL_EMAILS) p.save() if self.data['screenshot']: screenshot = Screenshot.objects.create( url=self.cleaned_data['screenshot'], small_thumbnail=self.cleaned_data['screenshot_thumbnail'], ordering=1, app=p) screenshot.save() if not p.is_integration or p.approved or user.is_superuser: return app_id
class FormFieldsetForm(FormFieldsetMixIn, Form): single_choices = [ ('A', 'Option A'), ('B', 'Option B'), ('C', 'Option C'), ] multi_choices = [ ('A', 'Include A'), ('B', 'Include B'), ('C', 'Include C'), ] DEFAULT_CITY = 'Seattle' DEFAULT_COUNTRY_AREA_STATE = 'WA' # Already imported DEFAULT_COUNTRY first = CharField(initial='first_value') second = CharField(initial='second_value') first_name = CharField(initial='first_name') last_name = CharField(initial='last_name') generic_field = CharField(initial='original_value') billing_address_1 = CharField( label='street address (line 1)', max_length=191, required=False, ) billing_address_2 = CharField( label='street address (continued)', max_length=191, required=False, ) billing_city = CharField( label='city', max_length=191, initial=DEFAULT_CITY, required=False, ) billing_country_area = CharField( label='state', max_length=2, initial=DEFAULT_COUNTRY_AREA_STATE, required=False, ) billing_postcode = CharField( label='zipcode', max_length=10, required=False, ) billing_country_code = CharField( label='country', initial=DEFAULT_COUNTRY, max_length=2, required=False, ) large_comment = CharField(initial='initial large comment', widget=Textarea(attrs={ "rows": 10, "cols": 40 })) small_comment = CharField(widget=Textarea(attrs={"rows": 2, "cols": 10})) simple_comment = CharField(widget=Textarea()) hide_field = CharField(widget=HiddenInput(), initial='hide_data') bool_field = BooleanField(required=False) # single checkbox single_select = ChoiceField( choices=single_choices) # default widget select multi_select = MultipleChoiceField(choices=multi_choices) # SelectMultiple radio_select = ChoiceField(choices=single_choices, widget=RadioSelect) single_check = ChoiceField(choices=single_choices, required=False, widget=CheckboxInput) # single/boolean choice multi_check = MultipleChoiceField(choices=multi_choices, widget=CheckboxSelectMultiple) email_test = EmailField( ) # like CharField, can have: max_length, min_length, and empty_value disable_field = CharField(disabled=True, initial='disable_data') another_field = CharField(initial='initial_data') last = CharField(initial='last_value') adjust_label_width = False called_prep_fields = False called_handle_modifiers = False called_assign_focus_field = False named_focus = None fields_focus = None hold_field = {} name_for_coded = 'generic_field' # Used for testing if 'coded' fieldset fieldnames work as needed. def prep_fields(self): """This is a placeholder to mock when FormOverrideMixIn is combined with this FormFieldsetMixIn. """ self.called_prep_fields = True return self.fields def handle_modifiers(self, opts, *args, **kwargs): """This is a placeholder to mock when FormOverrideMixIn is combined with this FormFieldsetMixIn. """ self.called_handle_modifiers = True remove_name = kwargs.pop('remove_field', None) add_name = kwargs.pop('add_field', None) if remove_name: self.hold_field.update({remove_name: self.fields.pop(remove_name)}) if add_name: if add_name not in self.hold_field: raise ValueError( f"Unable to retrieve {add_name} from {self.hold_field}") found = {add_name: self.hold_field.pop(add_name)} field_rows, remaining_fields, *fs_args = args remaining_fields.update(found) self.fields.update(found) args = (field_rows, remaining_fields, *fs_args) return (opts, *args, kwargs) def assign_focus_field(self, name=None, fields=None): """This is a placeholder to mock when FocusMixIn is combined with this FormFieldsetMixIn. """ self.called_assign_focus_field = True fields = fields or self.fields return name if name in fields else None
class IntegrationScaffoldingForm(Form): name = CharField(max_length=80, label=_('Integration name'), widget=TextInput()) author_homepage = URLField(label=_('Author\'s homepage'), required=False) issue_tracker = URLField(label=_('Issue tracker URL'), required=False, help_text=_('Bug reports and feature requests')) categories = MultipleChoiceField(widget=HiddenInput(), disabled=True, required=True, label=_('Categories'), choices=lazy(get_categories, list), help_text=_('Hold down Ctrl and click to ' 'select multiple entries')) summary = CharField( max_length=256, label=_('Summary'), help_text= _('Short description of your app that will be rendered as short teaser' )) screenshot = URLField(max_length=256, label=_('Screenshot URL'), required=False, help_text=_('URL for integration screenshot')) screenshot_thumbnail = URLField(max_length=256, label=_('Screenshot ' 'thumbnail URL'), required=False, help_text=_('URL for integration ' 'screenshot in ' 'smaller dimensions. ' 'Must be used in combination ' 'with a larger screenshot.')) description = CharField(widget=Textarea, label=_('Description'), help_text=_('Full description of what your' ' integration ' 'does. Can contain Markdown.')) def save(self, user, app_id, action): if app_id is None: app_id = self.cleaned_data['name'].lower().replace(" ", "_") try: app = App.objects.get(id=app_id) if app.can_update(user) or user.is_superuser: if action == "reject" and user.is_superuser: '''Not optimal but works''' Screenshot.objects.filter(app=app).delete() app.delete() elif action == "approve" and user.is_superuser: app.approved = True if settings.DISCOURSE_TOKEN: self._create_discourse_category(app_id) app.save() return app_id else: '''Not optimal but works''' Screenshot.objects.filter(app=app).delete() if self.data['screenshot']: screenshot = Screenshot.objects.create( url=self.cleaned_data['screenshot'], small_thumbnail=self. cleaned_data['screenshot_thumbnail'], ordering=1, app=app) screenshot.save() app.description = self.cleaned_data['description'] app.name = self.cleaned_data['name'] app.summary = self.cleaned_data['summary'] app.website = self.cleaned_data['author_homepage'] app.issue_tracker = self.cleaned_data['issue_tracker'] app.save() return app_id except App.DoesNotExist: app = App.objects.create(id=app_id, owner=user, certificate=uuid.uuid1().urn) app.set_current_language('en') app.categories.set(self.cleaned_data['categories']) app.description = self.cleaned_data['description'] app.name = self.cleaned_data['name'] app.summary = self.cleaned_data['summary'] app.website = self.cleaned_data['author_homepage'] app.issue_tracker = self.cleaned_data['issue_tracker'] app.save() p = App.objects.get(id=app_id) p.is_integration = True if user.is_superuser: p.approved = True if settings.DISCOURSE_TOKEN: self._create_discourse_category(app_id) else: send_mail( "New integration submitted", "Please review the " "integration to make " "sure it fits the " "guidelines.", settings.NEXTCLOUD_FROM_EMAIL, settings.NEXTCLOUD_INTEGRATIONS_APPROVAL_EMAILS) p.save() if self.data['screenshot']: screenshot = Screenshot.objects.create( url=self.cleaned_data['screenshot'], small_thumbnail=self.cleaned_data['screenshot_thumbnail'], ordering=1, app=p) screenshot.save() if not p.is_integration or p.approved or user.is_superuser: return app_id
def _create_field(self): """ :param cde: Common Data Element instance :return: A field object ( with widget possibly) We use a few conventions to find field class/widget class definitions. A check is made for any customised fields or widgets in the client app ( which must have name custom_fields.py.) The custom_fields module must contain functions with take a cde and return a field object. A custom field function must have name like custom_field_CDECODE23 ( assuming CDECODE23 is the code of the CDE) This function must return a field object. Then a check to look up any overrides based on code /datatype in this package is performed. Datatypes having their own field classes nust exist in the fields module class CustomFieldCDECod334 class DatatypeFieldSomeDatatypeName The same applies to special widgets we create class CustomWidgetCDECode233 class DatatypeEWidgetSomeDataTypeName Finally a Django field is returned based the DATATYPE_DICTIONARY ( if no field mapping is found a TextArea field is returned.) TODO Refactor this! """ options = self._get_field_options() if self._is_dropdown(): choices = self._get_permitted_value_choices() options['choices'] = choices options['initial'] = self.UNSET_CHOICE if self._has_other_please_specify(): other_please_specify_index = [ "other" in pair[0].lower() for pair in choices ].index(True) other_please_specify_value = choices[ other_please_specify_index][0] if self.cde.widget_name: try: widget_class = getattr(widgets, self.cde.widget_name) widget = widget_class(main_choices=choices, other_please_specify_value= other_please_specify_value, unset_value=self.UNSET_CHOICE) except BaseException: widget = widgets.OtherPleaseSpecifyWidget( main_choices=choices, other_please_specify_value= other_please_specify_value, unset_value=self.UNSET_CHOICE) else: widget = widgets.OtherPleaseSpecifyWidget( main_choices=choices, other_please_specify_value=other_please_specify_value, unset_value=self.UNSET_CHOICE) return fields.CharField(max_length=80, required=options.get( "required", False), help_text=_(self.cde.instructions), widget=widget, label=_(self.cde.name)) else: if self.cde.widget_name: widget = self._widget_search(self.cde.widget_name) else: widget = None if self.cde.allow_multiple: widget = widget or CheckboxSelectMultiple if widget: options['widget'] = widget options['choices'] = [ choice_pair for choice_pair in options['choices'] if choice_pair[1] != '---' ] return MultipleChoiceField(**options) else: if widget: options['widget'] = widget if "RadioSelect" in str(widget): # get rid of the unset choice options["choices"] = options['choices'][1:] if self.cde.code in [ "CDEPatientNextOfKinState", "CDEPatientNextOfKinCountry" ]: # These are dynamic now and alter their reange lists dynamically so have # to switch off validation from rdrf.forms.dynamic.fields import ChoiceFieldNoValidation return ChoiceFieldNoValidation(**options) if self.cde.code in ['State', 'Country']: # because these are dynamic lookup fields the usual validation wasn't # working from rdrf.forms.dynamic.fields import ChoiceFieldNonBlankValidation return ChoiceFieldNonBlankValidation(**options) return django.forms.ChoiceField(**options) else: # Not a drop down widget = None if self._has_field_override(): field = self._get_field_override() elif self._has_field_for_dataype(): field = self._get_field_for_datatype() else: if self._is_complex(): return self.complex_field_factory.create(options) # File Field if self._get_datatype() == 'file': return self._create_file_field(options) if self._is_calculated_field(): try: parser = CalculatedFieldScriptCreator( self.registry, self.registry_form, self.section, self.cde, injected_model=self.primary_model, injected_model_id=self.primary_id) script = parser.get_script() from rdrf.forms.widgets.widgets import CalculatedFieldWidget options['widget'] = CalculatedFieldWidget(script) return django.forms.CharField(**options) except CalculatedFieldScriptCreatorError as pe: logger.error("Calculated Field %s Error: %s" % (self.cde, pe)) field_or_tuple = self.DATATYPE_DICTIONARY.get( self.cde.datatype.lower(), django.forms.CharField) if isinstance(field_or_tuple, tuple): field = field_or_tuple[0] extra_options = field_or_tuple[1] options.update(extra_options) else: field = field_or_tuple if self.cde.widget_name: try: widget = self._widget_search(self.cde.widget_name) except Exception as ex: logger.error("Error setting widget %s for cde %s: %s" % (self.cde.widget_name, self.cde, ex)) raise ex widget = None else: if self.cde.datatype.lower() == 'date': from django.forms.extras.widgets import SelectDateWidget years = [yr for yr in range(1920, 2012, 1)] widget = SelectDateWidget(years=years) if self._has_widget_override(): widget = self._get_widget_override() elif self._has_widget_for_datatype(): widget = self._get_widget_for_datatype() if widget: options['widget'] = widget return field(**options)
class AddAssetForm(Form): """新增资产Form表单""" device_type_id = fields.ChoiceField( choices=models.Asset.device_type_choices, widget=widgets.Select( attrs={} ) ) device_status_id = fields.ChoiceField( choices=models.Asset.device_status_choices, widget=widgets.Select ) hostname = fields.CharField( error_messages={ "required": "主机名不能为空", }, widget=widgets.Input( attrs={"class": "form-control", "name": "hostname", "type": "text"}) ) cabinet_num = fields.CharField( required=False, widget=widgets.Input( attrs={"class": "form-control", "placeholder": "请输入机柜号,没有可为空", "name": "hostname", "type": "text"}) ) cabinet_order = fields.CharField( required=False, widget=widgets.Input( attrs={"class": "form-control", "placeholder": "请输入机柜中所在位置,没有可为空", "name": "hostname", "type": "text"}) ) idc_id = fields.ChoiceField( required=False, choices=[], widget=widgets.Select ) business_unit_id = fields.ChoiceField( required=False, choices=[], widget=widgets.Select ) tag = MultipleChoiceField( error_messages={ "required": "标签不能为空", }, choices=models.Tag.objects.all().values_list('id', 'name'), widget=widgets.CheckboxSelectMultiple ) def __init__(self, *args, **kwargs): super(AddAssetForm, self).__init__(*args, **kwargs) values = models.IDC.objects.all().values_list('id', 'name', 'floor') idc_values = [['', '---------']] for i in values: idc_values.append([i[0], "%s-%s" % (i[1], i[2])]) self.fields['idc_id'].choices = idc_values values = models.BusinessUnit.objects.values_list('id', 'name') business_unit_values = [['', '---------']] for i in values: business_unit_values.append([i[0], i[1]]) self.fields['business_unit_id'].choices = business_unit_values
class TVChannelsForm(forms.Form): channels = MultipleChoiceField(required=False, widget=CheckboxSelectMultiple())
class PreSelectedModelSearchForm(FacetedModelSearchForm): possible_facets = MultipleChoiceField(widget=CheckboxSelectMultiple, choices=(), required=False) connection = ChoiceField(choices=(), required=False) def __init__(self, *args, **kwargs): """ If we're in a recognised faceting engine, display and allow faceting. """ super(PreSelectedModelSearchForm, self).__init__(*args, **kwargs) # provide support for discovering the version installed. self.version = self.guess_haystack_version() if self.should_allow_faceting(): self.fields['possible_facets'].choices = self.configure_faceting() if self.has_multiple_connections(): self.fields['connection'].choices = self.get_possible_connections() self.fields['connection'].initial = 'default' else: self.fields['connection'].widget = HiddenInput() def is_haystack1(self): return getattr(settings, 'HAYSTACK_SEARCH_ENGINE', None) is not None def is_haystack2(self): return getattr(settings, 'HAYSTACK_CONNECTIONS', None) is not None def guess_haystack_version(self): if self.is_haystack1(): logger.debug("Guessed Haystack 1.2.x") return 1 if self.is_haystack2(): logger.debug("Guessed Haystack 2.x") return 2 return None def has_multiple_connections(self): if self.version == 1: return False elif self.version == 2: engine_2x = getattr(settings, 'HAYSTACK_CONNECTIONS', {}) return len(engine_2x) > 1 def get_possible_connections(self): engine_2x = getattr(settings, 'HAYSTACK_CONNECTIONS', {}) return ((force_text(x), force_text(x)) for x in sorted(engine_2x.keys())) def configure_faceting(self): if self.version == 2: from haystack import connections facet_fields = connections['default'].get_unified_index( )._facet_fieldnames possible_facets = facet_fields.keys() elif self.version == 1: possible_facets = [] for k, v in self.searchqueryset.site._field_mapping().items(): if v['facet_fieldname'] is not None: possible_facets.append(v['facet_fieldname']) return [(x, x) for x in possible_facets] def should_allow_faceting(self): if self.version == 1: engine_1x = getattr(settings, 'HAYSTACK_SEARCH_ENGINE', None) return engine_1x in ('solr', 'xapian') elif self.version == 2: engine_2x = getattr(settings, 'HAYSTACK_CONNECTIONS', {}) try: engine_2xdefault = engine_2x['default']['ENGINE'] ok_engines = ( 'solr' in engine_2xdefault, 'xapian' in engine_2xdefault, 'elasticsearch' in engine_2xdefault, ) return any(ok_engines) except KeyError as e: raise ImproperlyConfigured( "I think you're on Haystack 2.x without " "a `HAYSTACK_CONNECTIONS` dictionary") # I think this is unreachable, but for safety's sake we're going to # assume that if it got here, we can't know faceting is OK and working # so we'll disable the feature. return False def no_query_found(self): """ When nothing is entered, show everything, because it's a better useful default for our usage. """ return self.searchqueryset.all() def search(self): sqs = super(PreSelectedModelSearchForm, self).search() cleaned_data = getattr(self, 'cleaned_data', {}) to_facet_on = cleaned_data.get('possible_facets', []) connection = cleaned_data.get('connection', '') if self.has_multiple_connections() and connection: sqs = sqs.using(connection) if len(to_facet_on) > 0: for field in to_facet_on: sqs = sqs.facet(field) return sqs
def __init__(self, *args, space_id=None, request=None, geometry_editable=False, is_json=False, **kwargs): self.request = request super().__init__(*args, **kwargs) creating = not self.instance.pk if hasattr(self.instance, 'author_id'): if self.instance.author_id is None: self.instance.author = request.user if 'geometry' in self.fields: if not geometry_editable: # can't see this geometry in editor self.fields.pop('geometry') else: # hide geometry widget self.fields['geometry'].widget = HiddenInput() if not creating: self.initial['geometry'] = json.dumps(mapping(self.instance.geometry), separators=(',', ':')) if self._meta.model.__name__ == 'Source' and self.request.user.is_superuser: Source = self.request.changeset.wrap_model('Source') sources = {s['name']: s for s in Source.objects.all().values('name', 'access_restriction_id', 'left', 'bottom', 'right', 'top')} used_names = set(sources.keys()) all_names = set(os.listdir(settings.SOURCES_ROOT)) if not creating: used_names.remove(self.instance.name) all_names.add(self.instance.name) self.fields['name'].widget = Select(choices=tuple((s, s) for s in sorted(all_names-used_names))) if creating: for s in sources.values(): s['access_restriction'] = s['access_restriction_id'] del s['access_restriction_id'] self.fields['copy_from'] = ChoiceField( choices=tuple((('', '---------'), ))+tuple( (json.dumps(sources[name], separators=(',', ':'), cls=DjangoJSONEncoder), name) for name in sorted(used_names) ), required=False ) self.fields['fixed_x'] = DecimalField(label='fixed x', required=False, max_digits=7, decimal_places=3, initial=0) self.fields['fixed_y'] = DecimalField(label='fixed y', required=False, max_digits=7, decimal_places=3, initial=0) self.fields['scale_x'] = DecimalField(label='scale x (m/px)', required=False, max_digits=7, decimal_places=3, initial=1) self.fields['scale_y'] = DecimalField(label='scale y (m/px)', required=False, max_digits=7, decimal_places=3, initial=1) self.fields['lock_aspect'] = BooleanField(label='lock aspect ratio', required=False, initial=True) self.fields['lock_scale'] = BooleanField(label='lock scale (for moving)', required=False, initial=True) self.fields.move_to_end('lock_scale', last=False) self.fields.move_to_end('lock_aspect', last=False) self.fields.move_to_end('scale_y', last=False) self.fields.move_to_end('scale_x', last=False) self.fields.move_to_end('fixed_y', last=False) self.fields.move_to_end('fixed_x', last=False) self.fields.move_to_end('access_restriction', last=False) if creating: self.fields.move_to_end('copy_from', last=False) self.fields.move_to_end('name', last=False) if self._meta.model.__name__ == 'AccessRestriction': AccessRestrictionGroup = self.request.changeset.wrap_model('AccessRestrictionGroup') self.fields['groups'].label_from_instance = lambda obj: obj.title self.fields['groups'].queryset = AccessRestrictionGroup.qs_for_request(self.request) elif 'groups' in self.fields: LocationGroupCategory = self.request.changeset.wrap_model('LocationGroupCategory') kwargs = {'allow_'+self._meta.model._meta.default_related_name: True} categories = LocationGroupCategory.objects.filter(**kwargs).prefetch_related('groups') if self.instance.pk: instance_groups = tuple(self.instance.groups.values_list('pk', flat=True)) else: instance_groups = () self.fields.pop('groups') for category in categories: choices = tuple((str(group.pk), group.title) for group in sorted(category.groups.all(), key=self.sort_group)) category_groups = set(group.pk for group in category.groups.all()) initial = tuple(str(pk) for pk in instance_groups if pk in category_groups) if category.single: name = 'group_'+category.name initial = initial[0] if initial else '' choices = (('', '---'), )+choices field = ChoiceField(label=category.title, required=False, initial=initial, choices=choices, help_text=category.help_text) else: name = 'groups_'+category.name field = MultipleChoiceField(label=category.title_plural, required=False, initial=initial, choices=choices, help_text=category.help_text) self.fields[name] = field if 'label_settings' in self.fields: self.fields.move_to_end('label_settings') for field in tuple(self.fields.keys()): if field.startswith('label_override'): self.fields.move_to_end(field) if 'category' in self.fields: self.fields['category'].label_from_instance = attrgetter('title') if 'label_settings' in self.fields: self.fields['label_settings'].label_from_instance = attrgetter('title') if 'access_restriction' in self.fields: AccessRestriction = self.request.changeset.wrap_model('AccessRestriction') self.fields['access_restriction'].label_from_instance = lambda obj: obj.title self.fields['access_restriction'].queryset = AccessRestriction.qs_for_request(self.request) if 'base_mapdata_accessible' in self.fields: if not request.user.is_superuser: self.fields['base_mapdata_accessible'].disabled = True if space_id and 'target_space' in self.fields: Space = self.request.changeset.wrap_model('Space') GraphNode = self.request.changeset.wrap_model('GraphNode') GraphEdge = self.request.changeset.wrap_model('GraphEdge') cache_key = 'editor:neighbor_spaces:%s:%s%d' % ( self.request.changeset.raw_cache_key_by_changes, AccessPermission.cache_key_for_request(request, with_update=False), space_id ) other_spaces = cache.get(cache_key, None) if other_spaces is None: AccessPermission.cache_key_for_request(request, with_update=False) + ':' + str(request.user.pk or 0) space_nodes = set(GraphNode.objects.filter(space_id=space_id).values_list('pk', flat=True)) space_edges = GraphEdge.objects.filter( Q(from_node_id__in=space_nodes) | Q(to_node_id__in=space_nodes) ).values_list('from_node_id', 'to_node_id') other_nodes = set(chain(*space_edges)) - space_nodes other_spaces = set(GraphNode.objects.filter(pk__in=other_nodes).values_list('space_id', flat=True)) other_spaces.discard(space_id) cache.set(cache_key, other_spaces, 900) for space_field in ('origin_space', 'target_space'): other_space_id = getattr(self.instance, space_field+'_id', None) if other_space_id: other_spaces.add(other_space_id) space_qs = Space.qs_for_request(self.request).filter(pk__in=other_spaces) for space_field in ('origin_space', 'target_space'): if space_field in self.fields: self.fields[space_field].label_from_instance = lambda obj: obj.title self.fields[space_field].queryset = space_qs self.redirect_slugs = None self.add_redirect_slugs = None self.remove_redirect_slugs = None if 'slug' in self.fields: self.redirect_slugs = sorted(self.instance.redirects.values_list('slug', flat=True)) self.fields['redirect_slugs'] = CharField(label=_('Redirecting Slugs (comma separated)'), required=False, initial=','.join(self.redirect_slugs)) self.fields.move_to_end('redirect_slugs', last=False) self.fields.move_to_end('slug', last=False) if 'from_node' in self.fields: self.fields['from_node'].widget = HiddenInput() if 'to_node' in self.fields: self.fields['to_node'].widget = HiddenInput() if 'data' in self.fields and 'data' in self.initial: self.initial['data'] = json.dumps(self.initial['data']) self.is_json = is_json self.missing_fields = tuple((name, field) for name, field in self.fields.items() if name not in self.data and not field.required)
def __init__(self, *args, **kwargs): # kwargs: {'initial': {}, 'prefix': None, 'instance': <User: Truus>, 'request': <WSGIRequest: GET '/users/7/'>} self.request = kwargs.pop( 'request' ) # To get request.user. Do not use kwargs.pop('user', None) due to potential security hole super(UserEditForm, self).__init__(*args, **kwargs) self.request_user = self.request.user self.requestuser_company_id = 0 if self.request_user.company: self.requestuser_company_id = self.request_user.company.id self.this_instance = kwargs.get('instance') # this one doesn't work - selected_username does not show in form PPR2019-07-29 #kwargs.update({'selected_username': self.this_instance.username_sliced}) self.selecteduser_company_id = 0 if self.this_instance.company: self.selecteduser_company_id = self.this_instance.company.id # ======= field 'Company' ============ # PR2018-11-03 lock filed Company. self.fields['company'].disabled = True # ======= field 'first_name' ============ # field 'first_name' stores username_sliced without 000001, # field 'first_name' is not in use self.fields['first_name'].disabled = True # ======= field 'dep_list' ============ # TODO: Show only departments of selected school / examyear #dep_choices = Department.dep_list_choices(country=self.request.user.country) #self.fields['dep_list_field'] = MultipleChoiceField( # required=False, # widget=SelectMultiple, # choices=dep_choices, # label=_('Departments'), # help_text=_('Select the departments where this user has access to. ' # 'Press the Ctrl button to select multiple departments.') #) # ======= field 'department_field' ============ # get value of selected_user_department_id # TODO correct into departmentbase #self.selected_user_department_id = 0 #if self.this_instance.department: # self.selected_user_department_id = self.this_instance.department.id # give value to _choices # TODO: Show only departments of selected school / examyear #dep_choices = Department.dep_list_choices( # country=self.request.user.country, ## # init_list_str=self.this_instance.dep_list # ) #self.fields['department_field'] = ChoiceField( # required=False, # choises must be tuple or list, dictionary gives error: 'int' object is not iterable # choices=dep_choices, # label=_('Department'), # PR2018-07-31 debug: use schooldefault.id instead of schooldefault. # This showed always first item in choices: initial=self.this_instance.schooldefault # TODO correct into departmentbase # initial=self.selected_user_department_id #) # ======= field 'Permits' ============ self.permits_tuple = self.this_instance.permits_tuple self.fields['permit_list'] = MultipleChoiceField( required=False, widget=SelectMultiple, # choises must be tuple or list, dictionary gives error: 'int' object is not iterable choices=self.request.user.permits_choices, label='Permissions', help_text= _('Select one or more permissions from the list. Press the Ctrl button to select multiple permissions.' ), initial=self.permits_tuple) # ======= field 'is_active' ============ # PR2018-06-22, value in is_active is stored as str: '0'=False, '1'=True __initial_is_active = 0 if self.this_instance.is_active is not None: __initial_is_active = int(self.this_instance.is_active) self.fields['field_is_active'] = ChoiceField( choices=c.IS_ACTIVE_CHOICES, label=_('Active'), initial=__initial_is_active)
class SomeForm(Form): field = MultipleChoiceField(choices=[('one', 'One')])
class PluginUpdateForm(Form): jails = MultipleChoiceField(required=True) def __init__(self, *args, **kwargs): kwargs.pop('oid') super(PluginUpdateForm, self).__init__(*args, **kwargs)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['restricted_fields'] = MultipleChoiceField( choices=self.fields_choices) self.fields['layer'].queryset = Layer.vectors.all()
def __init__(self, *args, **kwargs): self.cid = kwargs.pop('course_id') self.course_id = Course.objects.get_record_by_id(self.cid) super().__init__(*args, **kwargs) FORMS = (('aktywność', 'aktywność'), ('egzamin', 'egzamin'), ('kartkówka', 'kartkówka'), ('kolokwium', 'kolokwium'), ('lista zadań', 'lista zadań')) TYPES = ( ('punkty', 'punkty'), ('ocena', 'ocena'), ('procenty', 'procenty'), ) i = 1 self.fields['ects'] = IntegerField(min_value=0, max_value=30) self.fields[ 'ects'].label = '{0:d}. Wpisz ile punktów ECTS ma kurs:'.format(i) i += 1 self.fields['formy'] = MultipleChoiceField( widget=CheckboxSelectMultiple, choices=FORMS) self.fields[ 'formy'].label = '{0:d}. Wybierz formy uzyskania ocen cząstkowych na kursie:'.format( i) i += 1 self.fields['form_type'] = ChoiceField(choices=TYPES, required=False) self.fields[ 'form_type'].label = '{0:d}. Zaznacz rodzaj oceniania na kursie:'.format( i) i += 1 YN = (('Tak', 'Tak'), ('Nie', 'Nie')) self.fields['mod_plus'] = ChoiceField(choices=YN) self.fields[ 'mod_plus'].label = '{0:d}. Czy możliwe jest podwyższenie oceny?'.format( i) i += 1 self.fields['mod_plus_w'] = FloatField(min_value=0, required=False) self.fields[ 'mod_plus_w'].label = 'Wpisz o ile ocena może zostać podwyższona:' self.fields['mod_minus'] = ChoiceField(choices=YN) self.fields[ 'mod_minus'].label = '{0:d}. Czy możliwe jest obniżenie oceny?'.format( i) i += 1 self.fields['mod_minus_w'] = FloatField(min_value=0, required=False) self.fields[ 'mod_minus_w'].label = 'Wpisz o ile ocena może zostać obniżona:' self.fields['mod_type'] = ChoiceField(choices=TYPES, required=False) self.fields[ 'mod_type'].label = '{0:d}. Wybierz w jakim typie jest modyfikacja oceny:'.format( i) i += 1 for key in self.fields: self.fields[key].error_messages[ 'required'] = "To pole jest wymagane." if 'invalid' in self.fields[key].error_messages: self.fields[key].error_messages[ 'invalid'] = 'To nie jest poprawna wartość' if 'min_value' in self.fields[key].error_messages: self.fields[key].error_messages[ 'min_value'] = 'To nie jest poprawna wartość' if 'max_value' in self.fields[key].error_messages: self.fields[key].error_messages[ 'max_value'] = 'To nie jest poprawna wartość'
def test_multiplechoicefield_1(self): f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')]) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean('') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) self.assertEqual(['1'], f.clean([1])) self.assertEqual(['1'], f.clean(['1'])) self.assertEqual(['1', '2'], f.clean(['1', '2'])) self.assertEqual(['1', '2'], f.clean([1, '2'])) self.assertEqual(['1', '2'], f.clean((1, '2'))) with self.assertRaisesMessage(ValidationError, "'Enter a list of values.'"): f.clean('hello') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean([]) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(()) msg = "'Select a valid choice. 3 is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): f.clean(['3'])
def fill_edit(self): enum_form = { 'ACTIV': 'aktywność', 'EXAM': 'egzamin', 'QUIZ': 'kartkówka', 'TEST': 'kolokwium', 'LIST': 'lista zadań' } enum_type = {'PKT': 'punkty', 'PERC': 'procenty', 'MARK': 'ocena'} FORMS = (('aktywność', 'aktywność'), ('egzamin', 'egzamin'), ('kartkówka', 'kartkówka'), ('kolokwium', 'kolokwium'), ('lista zadań', 'lista zadań')) TYPES = ( ('punkty', 'punkty'), ('ocena', 'ocena'), ('procenty', 'procenty'), ) YN = (('Tak', 'Tak'), ('Nie', 'Nie')) comp = Components.objects.get_records_by_course_id(self.course_id) ects = self.course_id.ECTS mod = Modyfication.objects.get_records_by_course_id(self.course_id) i = 1 self.fields['ects'] = IntegerField(min_value=0, max_value=30, initial=ects) self.fields[ 'ects'].label = '{0:d}. Wpisz ile punktów ECTS ma kurs:'.format(i) i += 1 init_comp = [] for c in comp: init_comp.append(enum_form[c.form]) self.fields['formy'] = MultipleChoiceField( widget=CheckboxSelectMultiple, choices=FORMS, initial=init_comp) self.fields[ 'formy'].label = '{0:d}. Wybierz formy uzyskania ocen cząstkowych na kursie:'.format( i) i += 1 c = enum_type[comp[0].type] self.fields['form_type'] = ChoiceField(choices=TYPES, required=False, initial=c) self.fields[ 'form_type'].label = '{0:d}. Zaznacz rodzaj oceniania na kursie:'.format( i) i += 1 self.fields['mod_plus'] = ChoiceField(choices=YN, initial='Nie') self.fields['mod_plus_w'] = FloatField(min_value=0, required=False) if mod: for m in mod: if m.mod == 'PLUS': self.fields['mod_plus'] = ChoiceField(choices=YN, initial='Tak') self.fields['mod_plus_w'] = FloatField(min_value=0, required=False, initial=m.val) self.fields[ 'mod_plus'].label = '{0:d}. Czy możliwe jest podwyższenie oceny?'.format( i) i += 1 self.fields[ 'mod_plus_w'].label = 'Wpisz o ile ocena może zostać podwyższona:' self.fields['mod_minus'] = ChoiceField(choices=YN, initial='Nie') self.fields['mod_minus_w'] = FloatField(min_value=0, required=False) self.fields['mod_type'] = ChoiceField(choices=TYPES, required=False) if mod: for m in mod: if m.mod == 'MINUS': self.fields['mod_minus'] = ChoiceField(choices=YN, initial='Tak') t = enum_type[m.type] self.fields['mod_minus_t'] = ChoiceField(choices=TYPES, required=False, initial=t) self.fields['mod_type'] = ChoiceField(choices=TYPES, required=False, initial=m.val) self.fields[ 'mod_minus'].label = '{0:d}. Czy możliwe jest obniżenie oceny?'.format( i) i += 1 self.fields[ 'mod_minus_w'].label = 'Wpisz o ile ocena może zostać obniżona:' self.fields[ 'mod_type'].label = '{0:d}. Wybierz w jakim typie jest modyfikacja oceny:'.format( i) i += 1
class SearchForm(Form): keyword = CharField(widget=BootstrapTextInput, max_length=100, initial="*") content_type = MultipleChoiceField(widget=BootstrapSelectMultiple, choices=PREDEFINED_CONTENT_TYPES, initial={'*': [1, 2]})
def fill_edit(self): YN = (('Tak', 'Tak'), ('Nie', 'Nie')) COURSES = ( ('ćwiczenia', 'ćwiczenia'), ('laboratorium', 'laboratorium'), ) cg = CourseGroup.objects.get_records_by_course_id(self.course_id) group = False if cg.exists(): group = True comp = Components.objects.get_records_by_course_id(self.course_id) ects = self.course_id.ECTS mod = Modyfication.objects.get_records_by_course_id(self.course_id) if group: self.fields['if_cg'] = ChoiceField(choices=YN, initial="Tak") else: self.fields['if_cg'] = ChoiceField(choices=YN, initial="Nie") self.fields['if_cg'].label = '1. Czy kurs jest częścią grupy kursów?' my_list = [] weight_list = [("", ""), ("", ""), ("", "")] all_types = Course.objects.get_all_types_by_id(self.course_id.id) if all_types: for el in all_types: if group: if el.type == "C": my_list.append("ćwiczenia") weight_list[0] = (el.coursegroup.weight, el.coursegroup.minimum) if el.type == "L": my_list.append("laboratorium") weight_list[1] = (el.coursegroup.weight, el.coursegroup.minimum) if el.type == "W": weight_list[2] = (el.coursegroup.weight, el.coursegroup.minimum) self.fields['courses'] = MultipleChoiceField( widget=CheckboxSelectMultiple, choices=COURSES, required=False, initial=my_list) self.fields[ 'courses'].label = '2. Zaznacz formy, w których odbywają się zajęcia w ramach grupy kursów:' self.fields['weight_c'] = FloatField(min_value=0, max_value=1, required=False, initial=weight_list[0][0]) self.fields[ 'weight_c'].label = '3. Wpisz udział oceny z ćwiczeń w ocenie końcowej z grupy kursów:' self.fields['weight_l'] = FloatField(min_value=0, max_value=1, required=False, initial=weight_list[1][0]) self.fields[ 'weight_l'].label = '4. Wpisz udział oceny z laboratorium w ocenie końcowej z grupy kursów:' self.fields['weight_w'] = FloatField(min_value=0, max_value=1, required=False, initial=weight_list[2][0]) self.fields[ 'weight_w'].label = '5. Wpisz udział oceny z wykładu w ocenie końcowej z grupy kursów:' if weight_list[0] != " " and weight_list[0][1]: self.fields['minimum'] = ChoiceField(choices=YN, initial="Tak") else: self.fields['minimum'] = ChoiceField(choices=YN, initial="Nie") self.fields[ 'minimum'].label = '6. Czy oceny z wszystkich kursów wchodzących w grupę muszą być większe niż 2?'
class OptionCheckbox(BaseOptionAnswer): answer = MultipleChoiceField(widget=CheckboxSelectMultiple)
def test_disabled_has_changed(self): f = MultipleChoiceField(choices=[("1", "One"), ("2", "Two")], disabled=True) self.assertIs(f.has_changed("x", "y"), False)