django 模型在选择字段上形成初始值

django model form initial value on choicefield

我正在尝试在 Django 的选择字段上设置初始值,但它似乎不起作用,而且我不确定我可以为选择字段设置什么初始值(即它应该是 const值,元组值..?)

型号:

class User(models.Model):
    DUAL_SUPPLIER = 'D'
    SEPERATE_SUPPLIERS = 'G'
    SINGLE_SUPPLIER = 'F'
    SERVICE_TYPE_CHOICES = ((DUAL_SUPPLIER, 'I have one supplier'),
                            (SEPERATE_SUPPLIERS, 'I have separate Suppliers'),
                            (SINGLE_SUPPLIER, 'I have a single supplier only'))
    service_type = models.CharField(max_length=10, choices=SERVICE_TYPE_CHOICES)
    online_account = models.BooleanField()

表格:

class SupplyTypeForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ('service_type', 'online_account')
        labels = {
            'service_type': 'What type of supplier do you have?',
            'online_account': 'Do you have an online account with any of your  suppliers',
        }
        initial = {
            'service_type': 'D'
        }

您需要在初始化表单时执行此操作:

form = SupplyTypeForm(request.POST or None, 
                      initial={'service_type': User.DUAL_SUPPLIER})

或者在表单的构造函数中执行:

class SupplyTypeForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(SupplyTypeForm, self).__init__(*args, **kwargs)
        self.fields['sevice_type'].initial = User.DUAL_SUPPLIER

初始化表单时设置初始值

form = SupplyTypeForm(initial={'service_type': 'D'})

或格式 class:

class SupplyTypeForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(SupplyTypeForm, self).__init__(*args, **kwargs)

        self.initial['service_type'] = 'D'