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:
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?
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With