[Django]-Django RadioSelect Choices From Model

11👍

This is a widget-level choice, not a field-level choice, and the built-in RadioSelect widget does exactly what you’re looking for:

https://docs.djangoproject.com/en/dev/ref/forms/widgets/#radioselect

Assuming you like its rendering choices, anyway. If not you can subclass, or on sufficiently recent versions loop over the choices in your template.

To use it, use a ModelChoiceField with the widget argument specified:

denomination = forms.ModelChoiceField(queryset=Denomination.objects.all(), widget=forms.RadioSelect)

Or, if you’re using a ModelForm:

class GiftCardForm(forms.ModelForm):
    class Meta:
        model = Gift_Card
        widgets = {'denomination': forms.RadioSelect}

Leave a comment