Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I think the best way of explaining is to walk through <a href="http://code.djangoproject.com/browser/django/trunk/django/forms/fields.py" rel="nofollow noreferrer">the code</a> for <code>ChoiceField</code>, the superclass of <code>TypeChoiceField</code>.</p> <pre><code>class ChoiceField(Field): widget = Select default_error_messages = { 'invalid_choice': _(u'Select a valid choice. %(value)s is not one of the available choices.'), } def __init__(self, choices=(), required=True, widget=None, label=None, initial=None, help_text=None, *args, **kwargs): super(ChoiceField, self).__init__(required=required, widget=widget, label=label, initial=initial, help_text=help_text, *args, **kwargs) self.choices = choices def _get_choices(self): return self._choices def _set_choices(self, value): # Setting choices also sets the choices on the widget. # choices can be any iterable, but we call list() on it because # it will be consumed more than once. self._choices = self.widget.choices = list(value) choices = property(_get_choices, _set_choices) </code></pre> <p>With your example,</p> <pre><code> self.fields['attending_ceremony'] = forms.TypedChoiceField( required=True, widget=forms.RadioSelect(choices=Guest.CHOICES) ) </code></pre> <ol> <li>The widget is initialised, with choices=guest.Choices</li> <li><code>super(ChoiceField, self).__init__</code> sets self.widget=widget. The widget's choices are still set.</li> <li><code>self.choices=choices</code> sets the choices for the field <em>and</em> the widget to the default <code>()</code>, because it wasn't specified (see <code>_set_choices</code> above).</li> </ol> <p>Hope that makes sense. Looking at the code also explains why your other examples work. Either the choices are set for the widget and the choice field at the same time, or widget's choices are set after the choice field has been initialised.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload