# HG changeset patch # User Olly Cope # Date 1636715458 0 # Fri Nov 12 11:10:58 2021 +0000 # Node ID be8cbf23a3b17b2b2995588770aac5178f85b580 # Parent b87bcd67b9a285c27e97e324c9fc44b56a2984a0 choices: add widgets.StrChoiceMapper and make this the default diff --git a/doc/fields.rst b/doc/fields.rst --- a/doc/fields.rst +++ b/doc/fields.rst @@ -131,22 +131,29 @@ validate_choices=False) -Choice fields are keyed on the json encoded representation of the value. -The ``value_mapper`` argument can override this. +Mapping choice values to strings +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When rendered in HTML forms choice values must be converted to strings, and then back again when the form is submitted and processed. -The default strategy is to convert your choice keys to a JSON representation. -This handles the common cases of strings and integer keys well (and also -``None``). +Starting from version 2.0, :class:`morf.fields.Choice` fields with non-string +values will have their values converted to strings when rendered in HTML. + +Two other options exist. -An alternative implementation is offered, which adds a key based on a simple indexing of the items based on their position in the list. For example, the choices:: +:class:`~morf.widgets.JSONChoiceMapper` converts choice values to JSON when rendering as HTML. This was the default behaviour prior to v2.0. + +:class:`~morf.widgets.IndexChoiceMapper` uses the position of each value in the choice list as the key. For example, the choices: + +..code-block::python [('11:00', 'Elevenses'), ('13:00', 'Lunch time'), ('16:00', 'Tea time')] Would result in options indexed as follows:: +..code-block::html + ' - '' - '' + '' + '' "" ) @@ -235,10 +235,10 @@ widget = widgets.Select() field = copy(self.field) field.choices = ["a", "a"] - expect(self.rendered({"s": '"a"'}, widget=widget, field=field)) == ( + expect(self.rendered({"s": "a"}, widget=widget, field=field)) == ( '" ) @@ -281,7 +281,7 @@ r = f.as_p().render() expect(r).contains('' '' '