[英]Django RadioSelect Choices From Model
So lets say I have the following model in my Django app: 所以我可以说我的Django应用程序中有以下模型:
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 . 我有一个表格来写我的Django应用程序中的卡片,并且有一个数量字段(很容易),一个礼品卡名称字段(用于验证,再次,很容易),我希望有一个无线电选择字段 。 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: 这是一个小部件级别的选择,而不是字段级别的选择,内置的RadioSelect
小部件完全符合您的要求:
https://docs.djangoproject.com/en/dev/ref/forms/widgets/#radioselect 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: 要使用它,请使用ModelChoiceField并指定widget
参数:
denomination = forms.ModelChoiceField(queryset=Denomination.objects.all(), widget=forms.RadioSelect)
Or, if you're using a ModelForm: 或者,如果您使用的是ModelForm:
class GiftCardForm(forms.ModelForm):
class Meta:
model = Gift_Card
widgets = {'denomination': forms.RadioSelect}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.