简体   繁体   中英

django model form initial value on choicefield

I'm trying to set the initial value on a choicefield on django but it doesn't seem to work and I'm not sure what I can set the initial values to for a choicefield (ie should it the const value, tuple value..?)

model:

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()

Form:

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'
        }

You need to do it when you initialize your form:

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

Or do it in the constructor of the form:

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

Set initial value when you initialize the form

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

Or in the form class:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM