diff options
Diffstat (limited to 'ishtar_common/forms.py')
| -rw-r--r-- | ishtar_common/forms.py | 29 | 
1 files changed, 28 insertions, 1 deletions
| diff --git a/ishtar_common/forms.py b/ishtar_common/forms.py index 5de0db91d..59f3e141a 100644 --- a/ishtar_common/forms.py +++ b/ishtar_common/forms.py @@ -26,6 +26,7 @@ import re  import types  from django import forms +from django.contrib.contenttypes.models import ContentType  from django.core.urlresolvers import reverse  from django.core import validators  from django.forms.formsets import BaseFormSet, DELETION_FIELD_NAME @@ -114,7 +115,7 @@ JSON_VALUE_TYPES_FIELDS = {      'I': (forms.IntegerField, None),      'F': (forms.FloatField, None),      'D': (DateField, None), -    'C': (forms.CharField, None), +    'C': (widgets.Select2DynamicField, None),  } @@ -171,6 +172,30 @@ class CustomForm(object):              self.fields.pop(key)      @classmethod +    def _get_dynamic_choices(cls, key): +        """ +        Get choice from existing values +        :param key: data key +        :return: tuple of choices (id, value) +        """ +        app_name = cls.__module__.split('.')[0] +        if app_name == "archaeological_files_pdl": +            app_name = "archaeological_files" +        model_name = cls.form_slug.split("-")[0].replace('_', "") +        ct = ContentType.objects.get(app_label=app_name, model=model_name) +        ct_class = ct.model_class() +        choices = set() +        splitted_key = key[len('data__'):].split('__') +        for obj in ct_class.objects.filter( +                data__has_key=key[len('data__'):]).all(): +            value = obj.data +            for k in splitted_key: +                value = value[k] +            choices.add(value) +        choices = [('--', '')] + [(v, v) for v in sorted(list(choices))] +        return choices + +    @classmethod      def _get_json_fields(cls, custom_form):          fields = []          for field in custom_form.json_fields.order_by('order').all(): @@ -185,6 +210,8 @@ class CustomForm(object):                  attrs['help_text'] = field.help_text              if widget:                  attrs['widget'] = widget(attrs={"class": "form-control"}) +            if field_cls == widgets.Select2DynamicField: +                attrs['choices'] = cls._get_dynamic_choices(key)              f = field_cls(**attrs)              fields.append((field.order or 1, key, f))          return fields | 
