Skip to content

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

@Doskious

Description

@Doskious

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions