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

时间:2016-01-25 15:46:42

标签: python django django-forms

我试图在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'
        }

2 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:0)

初始化表单时设置初始值

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

或者在表格类中:

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

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