﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
27758	Template widget rendering breaks the AdvancedModelIterator pattern	Jon Dufresne	nobody	"Occasionally, when extending `ModelChoiceField` and `ModelMultipleChoiceField` with a custom widget, it is useful for the widget to know the object used to create the value, label pair. This could be used to adding custom HTML attributes to very specific choices.

Historically, a pattern was developed to handle this situation named [http://srcmvn.com/blog/2013/01/15/django-advanced-model-choice-field AdvancedModelChoiceIterator]. The pattern described in the article breaks in 1.11.

Firstly, `ChoiceWidget` now always expects a 2-tuple returned by `ModelChoiceIterator.choice()` as it is unpacked in [https://github.com/django/django/blob/a15d81a183e2d85969ed46adb975661515330b16/django/forms/widgets.py#L573 ChoiceWidget.optgroups()]. The usage is [https://docs.djangoproject.com/en/1.10/ref/forms/fields/#django.forms.ChoiceField.choices documented] as requiring a 2-tuple, so maybe this is considered OK.

An alternative I considered was returning a wrapped value to hold the object, hoping this would be accessible from `ChoiceWidget.create_option()`. Unfortunately this did not work as the value is eagerly coerced to a string very early in [https://github.com/django/django/blob/a15d81a183e2d85969ed46adb975661515330b16/django/forms/widgets.py#L577 ChoiceWidget.optgroups()]. For example:

{{{
class AdvancedChoiceValue:
    def __init__(self, value, obj):
        self.value = value
        self.obj = obj

    def __str__(self):
        return str(self.value)


class AdvancedChoiceIterator(ModelChoiceIterator):
    def choice(self, obj):
        value, label = super().choice(obj)
        return AdvancedChoiceValue(value, obj), label
}}}


I think delaying the `force_text()` until checking the selected value would solve this problem.
"	Bug	closed	Forms	1.11	Release blocker	fixed		Preston Timmons	Accepted	1	0	0	0	0	0
