Django RadioSelect Choices From Model

django, forms, model, python, radio-button

Solution

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}

Problem

So lets say I have the following model in my Django app: ``` class Gift_Card(models.Model): title = models.CharField(blah blah) company = models.CharField(blah blah) denomination = models.ForeignKey('Denomination') class Denomination(models.Model): is_subscription = models.BooleanField(blah blah) is_money = models.BooleanField(blah blah) amount = models.IntegerField(blah blah) ``` It's poorly written, but this is what I'm going for: - Generic gift card model - Support for many types of amounts (1 year subscription card, $20 gift card, etc) I have a form written to request a card from my Django app, and there is a quantity field (easy enough), a giftcard name field (for verification, and again, easy enough), and I want there to be a radio selection field. The radio selection field should be populated with the denomination model relevant to the gift card at hand. However, I'm unsure how to do that. Any help?

Original source