如果想要灵活应用ChoiceField,那么请看如下:
class TransactionRecord(ActiveBaseModel):
""" 交易记录 """
charge_type_class_mapping = {
1: "success",
2: "danger",
3: "default",
4: "info",
5: "primary",
}
charge_type_choices = ((1, "充值"), (2, "扣款"), (3, "创建订单"), (4, "删除订单"), (5, "撤单"),)
class ChargeModelForm(BootStrapForm, forms.ModelForm):
# 方式1:
# 静态变量(程序启动,就加载到内存中了)
charge_type = forms.ChoiceField(
label="类型",
choices=[(1, '充值'), (2, '扣款')], # 只适合固定的数据,不适合去数据表中获取数据
)
# creator = forms.ChoiceField(
# label='管理员',
# choices=models.Administrator.objects.filter(id__gt=1).values_list("id", "username")
# )
class Meta:
model = models.TransactionRecord
fields = ['charge_type', 'amount']
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# 方式2:
# 每次实例化对象试,都会重新获取数据
# self.fields['charge_type'].choices = [(1, '扣款'), (2, '充值')]
标签:__,14,type,Django,forms,charge,ChoiceField,class
From: https://www.cnblogs.com/it-lkp/p/16588666.html