def __init__(self, field_items, skip_check=False, *args, **kwargs): self.field_dict = OrderedDict(field_items) self.skip_check = skip_check # Make sure no subfield is named 'SKIP_CHECK_NAME'. If # skip_check is True this field will clash with the addtional # subfield added by the DictCharField constructor. We perform # this check even if skip_check=False because having a field named # 'skip_check' that isn't used to actually skip the checks would be # very confusing. if SKIP_CHECK_NAME in self.field_dict: raise RuntimeError("'%s' is a reserved name " "(it can't be used to name a subfield)." % SKIP_CHECK_NAME) # if skip_check: add a BooleanField to the list of fields, this will # be used to skip the validation of the fields and accept arbitrary # data. if skip_check: self.field_dict[SKIP_CHECK_NAME] = forms.BooleanField( required=False) self.names = [name for name in self.field_dict] # Create the DictCharWidget with init values from the list of fields. self.fields = list(self.field_dict.values()) self.widget = DictCharWidget( [field.widget for field in self.fields], self.names, [field.initial for field in self.fields], [field.label for field in self.fields], skip_check=skip_check, ) # Upcall to Field and not MultiValueField to avoid setting all the # subfields' 'required' attributes to False. Field.__init__(self, *args, **kwargs)
def __init__(self, queryset, empty_label="---------", cache_choices=False, required=True, widget=None, label=None, initial=None, help_text=None, to_field_name=None, *args, **kwargs): if required and (initial is not None): self.empty_label = None else: self.empty_label = empty_label self.cache_choices = cache_choices # Call Field instead of ChoiceField __init__() because we don't need # ChoiceField.__init__(). Field.__init__(self, required, widget, label, initial, help_text, *args, **kwargs) self.queryset = queryset self.choice_cache = None self.to_field_name = to_field_name
def __init__( self, queryset, empty_label="---------", cache_choices=False, required=True, widget=None, label=None, initial=None, help_text=None, to_field_name=None, *args, **kwargs ): if required and (initial is not None): self.empty_label = None else: self.empty_label = empty_label self.cache_choices = cache_choices # Call Field instead of ChoiceField __init__() because we don't need # ChoiceField.__init__(). Field.__init__(self, required, widget, label, initial, help_text, *args, **kwargs) self.queryset = queryset self.choice_cache = None self.to_field_name = to_field_name
def __init__(self, field_items, skip_check=False, *args, **kwargs): self.field_dict = OrderedDict(field_items) self.skip_check = skip_check # Make sure no subfield is named 'SKIP_CHECK_NAME'. If # skip_check is True this field will clash with the addtional # subfield added by the DictCharField constructor. We perform # this check even if skip_check=False because having a field named # 'skip_check' that isn't used to actually skip the checks would be # very confusing. if SKIP_CHECK_NAME in self.field_dict.keys(): raise RuntimeError( "'%s' is a reserved name " "(it can't be used to name a subfield)." % SKIP_CHECK_NAME) # if skip_check: add a BooleanField to the list of fields, this will # be used to skip the validation of the fields and accept arbitrary # data. if skip_check: self.field_dict[SKIP_CHECK_NAME] = forms.BooleanField( required=False) self.names = [name for name in self.field_dict.keys()] # Create the DictCharWidget with init values from the list of fields. self.fields = self.field_dict.values() self.widget = DictCharWidget( [field.widget for field in self.fields], self.names, [field.label for field in self.fields], skip_check=skip_check, ) # Upcall to Field and not MultiValueField to avoid setting all the # subfields' 'required' attributes to False. Field.__init__(self, *args, **kwargs)
def clean(self, value): Field.clean(self, value) if value in EMPTY_VALUES: return None res = False for q in self.queryset: if long(value) == q.id: res = True if not res: raise ValidationError(self.error_messages["invalid_choice"]) return value
def clean(self, value): Field.clean(self, value) if value in EMPTY_VALUES: return None res = False for q in self.queryset: if int(value) == q.id: res = True if not res: raise ValidationError(self.error_messages["invalid_choice"]) return value
def clean(self, value): Field.clean(self, value) if value in EMPTY_VALUES: return value values = self.split(value) error_list = [] for value in values: try: value = RegexField.clean(self, value) except ValidationError, e: error_list.append(value)
def clean(self, value): Field.clean(self, value) if value in EMPTY_VALUES: return None res = False for q in self.queryset: if hasattr(q.id, 'val'): if long(value) == q.id.val: res = True else: if long(value) == q.id: res = True if not res: raise ValidationError(self.error_messages['invalid_choice']) return value
def textinfo(cls, choice): attrs = { "placeholder": choice.get("extra_info_text"), "class": "extra-widget extra-widget-text", "style": "display: none;", } return Field(required=False, widget=TextInput(attrs=attrs))
class LeafletForm(ModelForm): map_position = Field(widget=widgets.HiddenInput) class Meta: fields = ['glossary'] def __init__(self, data=None, *args, **kwargs): try: initial = dict(kwargs['instance'].glossary) except (KeyError, AttributeError): initial = {} initial.update(kwargs.pop('initial', {})) map_position = initial.pop( 'map_position', app_settings.CMSPLUGIN_CASCADE['leaflet']['default_position']) initial['map_position'] = json.dumps(map_position) super(LeafletForm, self).__init__(data, initial=initial, *args, **kwargs) def clean(self): try: map_position = self.cleaned_data['map_position'] if isinstance(map_position, six.string_types): self.cleaned_data['glossary'].update( map_position=json.loads(map_position)) elif isinstance(map_position, dict): self.cleaned_data['glossary'].update(map_position=map_position) else: raise ValueError except (ValueError, KeyError): raise ValidationError( "Invalid internal position data. Check your Javascript imports." )
def ModelChoiceField__init__(self, queryset, empty_label=u"---------", cache_choices=False, required=True, widget=None, label=None, initial=None, help_text=None, to_field_name=None, *args, **kwargs): if required and (initial is not None): self.empty_label = None else: self.empty_label = empty_label self.cache_choices = cache_choices # Monkey starts here if self.__class__ in (ModelChoiceField, ModelMultipleChoiceField): meta = queryset.model._meta key = '%s.%s' % (meta.app_label, meta.module_name) # Handle both legacy settings SIMPLE_AUTOCOMPLETE_MODELS and new # setting SIMPLE_AUTOCOMPLETE. models = getattr(settings, 'SIMPLE_AUTOCOMPLETE_MODELS', getattr(settings, 'SIMPLE_AUTOCOMPLETE', {}).keys()) if key in models: pickled = pickle.dumps( (queryset.model._meta.app_label, queryset.model._meta.module_name, queryset.query)) token = hashlib.md5(pickled).hexdigest() _simple_autocomplete_queryset_cache[token] = pickled if self.__class__ == ModelChoiceField: widget = AutoCompleteWidget(token=token, model=queryset.model) else: widget = AutoCompleteMultipleWidget(token=token, model=queryset.model) # Monkey ends here # Call Field instead of ChoiceField __init__() because we don't need # ChoiceField.__init__(). Field.__init__(self, required, widget, label, initial, help_text, *args, **kwargs) self.queryset = queryset self.choice_cache = None self.to_field_name = to_field_name
def ModelChoiceField__init__(self, queryset, empty_label=u"---------", cache_choices=False, required=True, widget=None, label=None, initial=None, help_text=None, to_field_name=None, *args, **kwargs): if required and (initial is not None): self.empty_label = None else: self.empty_label = empty_label self.cache_choices = cache_choices # Monkey starts here if self.__class__ in (ModelChoiceField, ModelMultipleChoiceField): meta = queryset.model._meta key = '%s.%s' % (meta.app_label, meta.model_name) # Handle both legacy settings SIMPLE_AUTOCOMPLETE_MODELS and new # setting SIMPLE_AUTOCOMPLETE. models = getattr( settings, 'SIMPLE_AUTOCOMPLETE_MODELS', getattr(settings, 'SIMPLE_AUTOCOMPLETE', {}).keys() ) if key in models: pickled = pickle.dumps(( queryset.model._meta.app_label, queryset.model._meta.model_name, queryset.query )) token = hashlib.md5(pickled).hexdigest() _simple_autocomplete_queryset_cache[token] = pickled if self.__class__ == ModelChoiceField: widget = AutoCompleteWidget(token=token, model=queryset.model) else: widget = AutoCompleteMultipleWidget( token=token, model=queryset.model ) # Monkey ends here # Call Field instead of ChoiceField __init__() because we don't need # ChoiceField.__init__(). if 'limit_choices_to' in kwargs: kwargs.pop('limit_choices_to') Field.__init__(self, required, widget, label, initial, help_text, *args, **kwargs) self.queryset = queryset self.choice_cache = None self.to_field_name = to_field_name
def textinfo(cls, choice): attrs = { 'placeholder': choice.get('extra_info_text'), 'class': "extra-widget extra-widget-text", 'style': "display: none;", } return Field( required=False, widget=TextInput(attrs=attrs), )
def __init__(self, model, form=NestedInlineForm, fields=None, exclude=None, formfield_callback=None, widgets=None, localized_fields=None, labels=None, help_texts=None, error_messages=None, instance=None, required=True, widget=None, *args, **kwargs): """ __init__(self, model, form=NestedInlineForm, *args, **kwargs) """ self.model = model self.form_name = form self.fields = fields self.exclude = exclude self.formfield_callback = formfield_callback self.widgets = widgets self.localized_fields = localized_fields self.labels = labels self.help_texts = help_texts self.error_messages = error_messages self.instance = instance # Skip InlineForeignKeyField, we only need some of it's functionality. Field.__init__(self, required=required, widget=widget, *args, **kwargs)
def _formfield(self, initial): if not self.editable: raise Exception('This type is not editable.') return Field()
def validate(self, value): return Field.validate(self, value)
def __init__(self, lookup_name, *args, **kwargs): kwargs.pop('widget', 1) #dummy True value, to remove widget argument Field.__init__(self, widget=AutocompleteSelectMultiple(lookup_name, kwargs.pop('widget_attrs', {})), *args, **kwargs) AutocompleteField.__init__(self, lookup_name)
def __init__(self, lookup_name, *args, **kwargs): kwargs.pop('widget', 1) #dummy True value, to remove widget argument Field.__init__(self, widget=AutocompleteSelect(lookup_name, kwargs.pop('widget_attrs', {})), *args, **kwargs) #setting current widget as an autocomplete text input AutocompleteField.__init__(self, lookup_name)
def __init__(self, url, model=None, using=None, field=None, *args, **kwargs): self.model = model self.using = using self.field = field self.widget = AutocompleteWidget(url=url, field=field) Field.__init__(self, *args, **kwargs)
def get_form(self, request, obj=None, **kwargs): form = super(GalleryAdmin, self).get_form(request, obj=None, **kwargs) if obj: form.base_fields['upload'] = Field(widget=UploadWidget(obj=obj), required=False) return form
def __init__(self, model=None, field=None, *args, **kwargs): self.model = model self.field = field self.widget = AdminImageUploaderWidget(field=field,model=model,url='/admin/image/upload/') Field.__init__(self, *args, **kwargs)
class MarkerForm(ModelForm): title = CharField( label=_("Marker Title"), widget=widgets.TextInput(attrs={'size': 60}), help_text=_( "Please choose a title, then go to the map to set a marker pin")) use_icon = BooleanField( label=_("Use customized marker icon"), initial=False, required=False, ) marker_image = ModelChoiceField( queryset=Image.objects.all(), label=_("Marker Image"), required=False, ) marker_width = GlossaryFormField( widget=CascadingSizeWidget(allowed_units=['px'], required=False), label=_("Marker Width"), required=False, help_text=_("Width of the marker icon in pixels."), ) marker_anchor = GlossaryFormField( widget=MultipleCascadingSizeWidget(['left', 'top'], allowed_units=['px', '%'], required=False), required=False, label=_("Marker Anchor"), help_text= _("The coordinates of the icon's anchor (relative to its top left corner)." ), ) popup_text = HTMLFormField( required=False, help_text=_("Optional rich text to display in popup."), ) position = Field(widget=widgets.HiddenInput) glossary_field_order = [ 'title', 'marker_width', 'marker_anchor', 'popup_text' ] class Meta: exclude = ['glossary'] def __init__(self, *args, **kwargs): try: initial = dict(kwargs['instance'].glossary) has_original = True except (KeyError, AttributeError): initial = {} has_original = False initial.update(kwargs.pop('initial', {})) self.base_fields['position'].initial = json.dumps( initial.pop('position', {})) for key in self.glossary_field_order: self.base_fields[key].initial = initial.get(key) try: self.base_fields['marker_image'].initial = initial['image']['pk'] except KeyError: self.base_fields['marker_image'].initial = None self.base_fields['use_icon'].initial = False else: self.base_fields['use_icon'].initial = True self.base_fields['marker_image'].widget = AdminFileWidget( ManyToOneRel(FilerImageField, Image, 'file_ptr'), site) super(MarkerForm, self).__init__(*args, **kwargs) if has_original: self.fields['title'].help_text = None def clean(self): try: position = self.cleaned_data['position'] if isinstance(position, six.string_types): position = json.loads(position) elif not isinstance(position, dict): raise ValueError except (ValueError, KeyError): raise ValidationError( "Invalid internal position data. Check your Javascript imports." ) else: if 'lat' not in position or 'lng' not in position: # place the marker in the center of the current map position = { k: v for k, v in self.instance.cascade_element. glossary['map_position'].items() if k in ['lat', 'lng'] } self.instance.glossary.update(position=position) marker_image = self.cleaned_data.pop('marker_image', None) if marker_image: image_data = {'pk': marker_image.pk, 'model': 'filer.Image'} self.instance.glossary.update(image=image_data) else: self.instance.glossary.pop('image', None) popup_text = self.cleaned_data.pop('popup_text', None) if strip_tags(popup_text): popup_text = strip_spaces_between_tags(popup_text) self.cleaned_data.update(popup_text=popup_text) for key in self.glossary_field_order: self.instance.glossary.update({key: self.cleaned_data.get(key)})
def clean(self, value): value = Field.clean(self, value) # Skip parent class (other than Field) obj = value.save(commit=False) return obj
def prepare_value(self, value): if hasattr(value, 'to_primitive'): return json.dumps(type(value).to_primitive(value)) return Field.prepare_value(self, value)