summaryrefslogtreecommitdiff
path: root/ishtar_common/widgets.py
diff options
context:
space:
mode:
authorÉtienne Loks <etienne.loks@iggdrasil.net>2018-06-05 20:42:14 +0200
committerÉtienne Loks <etienne.loks@iggdrasil.net>2018-06-12 09:57:24 +0200
commit52f6b37f1a1deac66f0b84c466be6c8dab277514 (patch)
tree2e9d8c696298f89e33e713d4eaf2a4c1c48af3b5 /ishtar_common/widgets.py
parente7418c19b122c5ac0505ad2be5350068d3bf6f6b (diff)
downloadIshtar-52f6b37f1a1deac66f0b84c466be6c8dab277514.tar.bz2
Ishtar-52f6b37f1a1deac66f0b84c466be6c8dab277514.zip
Document form - refactoring (refs #4107)
Diffstat (limited to 'ishtar_common/widgets.py')
-rw-r--r--ishtar_common/widgets.py54
1 files changed, 53 insertions, 1 deletions
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={},