【发布时间】:2021-04-29 21:30:34
【问题描述】:
我正在使用的数据库有几个布尔字段,一次只有一个应该为真。 我想将它们格式化为 Select 小部件,以便我可以将每个布尔字段列为选项,并且将为除所选选项之外的所有布尔字段返回 False。
我将它们中的每一个单独用作复选框(我已将它们注释掉),并且我能够制作一个在视图中正确显示的选择小部件 (client_type),但我无法完成上述操作。
这是我的 models.py 的相关部分:
class DomCase(models.Model):
plaintiff = models.BooleanField(default=False, blank=True)
defendant = models.BooleanField(default=False, blank=True)
class DomCaseForm(ModelForm):
client_type = ChoiceField(choices=(('', '----'),('plaintiff', 'Plaintiff'),('defendant','Defendant')), widget=Select(attrs={'class': 'form-control', 'id': 'client_type'}))
class Meta:
model = DomCase
widgets = {
#'plaintiff': CheckboxInput(attrs={'class': 'custom-control-input', }),
#'defendant': CheckboxInput(attrs={'class': 'custom-control-input', }),
}
# Dynamically Create Form Fields based on widget details
fields = []
for widget in widgets:
fields.append(widget)
fields = tuple(fields)
【问题讨论】:
标签: django django-models django-forms