stephenmcd / django-forms-builder

Let users build forms in Django admin
BSD 2-Clause "Simplified" License
691 stars 281 forks source link

Option for JSON-formatted choices, to allow divergence between submitted values and displayed choices #228

Open Doskious opened 6 years ago

Doskious commented 6 years ago

Since it's often nice to be able to display text options that don't perfectly match the desired form submission values, and python comes with a pretty nice JSON parser built in, adding the ability to enter form field choices as JSON-formatted text would be nice. This would require an additional setting option to be configured, and could be served by the following code modifcation in forms_builder.forms.models at line 202.

def get_choices(self):
    """
    Parse a comma separated choice string into a list of choices taking
    into account quoted choices using the ``settings.CHOICES_QUOTE`` and
    ``settings.CHOICES_UNQUOTE`` settings.
    """
    if not settings.USE_JSON_CHOICES:
        choice = ""
        quoted = False
        for char in self.choices:
            if not quoted and char == settings.CHOICES_QUOTE:
                quoted = True
            elif quoted and char == settings.CHOICES_UNQUOTE:
                quoted = False
            elif char == "," and not quoted:
                choice = choice.strip()
                if choice:
                    yield choice, choice
                choice = ""
            else:
                choice += char
        choice = choice.strip()
        if choice:
            yield choice, choice
    else:
        import json  # noaq
        parsed = json.loads(self.choices)
        try:
            for value, choice in parsed.items():
                yield value, choice
        except AttributeError:
            if not isinstance(parsed, basestring):
                for choice in parsed:
                    yield choice, choice
            else:
                yield parsed, parsed