From 52f6b37f1a1deac66f0b84c466be6c8dab277514 Mon Sep 17 00:00:00 2001 From: Étienne Loks Date: Tue, 5 Jun 2018 20:42:14 +0200 Subject: Document form - refactoring (refs #4107) --- ishtar_common/widgets.py | 54 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 53 insertions(+), 1 deletion(-) (limited to 'ishtar_common/widgets.py') diff --git a/ishtar_common/widgets.py b/ishtar_common/widgets.py index a20d33fc3..6ec0220eb 100644 --- a/ishtar_common/widgets.py +++ b/ishtar_common/widgets.py @@ -458,6 +458,58 @@ class SearchWidget(forms.TextInput): template_name = 'widgets/search_input.html' +class ModelFieldMixin(object): + def to_python(self, value): + if not value: + return + if not self.multiple: + value = [value] + values = [] + for v in value: + if not v: + continue + try: + values.append(self.model.objects.get(pk=v)) + except self.model.DoesNotExist: + raise ValidationError( + unicode( + _(u"{} is not a valid key for {}") + ).format(v, self.model) + ) + if not self.multiple: + return values[0] + return values + + +class ModelChoiceField(ModelFieldMixin, forms.ChoiceField): + def __init__(self, model, multiple=False, *args, **kwargs): + self.model = model + self.multiple = multiple + super(ModelFieldMixin, self).__init__(*args, **kwargs) + + def valid_value(self, value): + if value and getattr(value, 'pk', None) in [v for v, l in self.choices]: + return True + return super(ModelChoiceField, self).valid_value(value) + + +class ModelJQueryAutocompleteField(ModelFieldMixin, forms.CharField): + def __init__(self, model, multiple=False, new=False, long_widget=False, + *args, **kwargs): + self.model = model + self.multiple = multiple + attrs = {} + if long_widget: + attrs['cols'] = True + attrs['full-width'] = True + kwargs['widget'] = JQueryAutoComplete( + reverse_lazy('autocomplete-' + self.model.SLUG), + associated_model=self.model, new=new, multiple=multiple, + attrs=attrs + ) + super(ModelJQueryAutocompleteField, self).__init__(*args, **kwargs) + + class JQueryAutoComplete(forms.TextInput): def __init__(self, source, associated_model=None, options=None, attrs=None, new=False, url_new='', multiple=False, limit=None, @@ -619,7 +671,7 @@ class JQueryAutoComplete(forms.TextInput): class JQueryTown(forms.TextInput): """ - Town fields whith state and department pre-selections + Town fields with state and department pre-selections """ def __init__(self, source, options={}, -- cgit v1.2.3