I have a MultipleChoiceField and for displaying the values that had been previous selected in the admin, I have to override method init from a ModelForm. I have the following class with its form:
class Profile(models.Model):
name = models.CharField(max_length=64)
contract = models.CharField(max_length=100)
class ProfileForm(forms.ModelForm):
CONTRACT_CHOICES = (
('scholar', _(u'Scholar')),
('freelance', _(u'Freelance')),
('contract', _(u'Contract')),
('volunteer', _(u'Volunteer'))
)
contract = forms.MultipleChoiceField(choices=CONTRACT_CHOICES)
def __init__(self, *args, **kwargs):
initial = kwargs.get('initial',{})
initial['contract'] = ['scholar', 'contract', 'freelance'] #Here I would have to be able to get the attribute contract from the Profile class, not this list
kwargs['initial'] = initial
super(ProfileForm, self).__init__(*args, **kwargs)
With the initial['contract']=['scholar','contract','freelance']
works (this values are shown as selected) but I have to achieve this with the attribute contract from Profile. I know that you can access to the model from a ModelForm with the attribute instance, but there's one problem: you can only have access to instance once the native method of init is called. And in this case, I have to call it later because otherwise it doesn't work for me. I already have tried to do it the following way:
def __init__(self, *args, **kwargs):
super(ProfileForm, self).__init__(*args, **kwargs)
self.fields['contract'].initial = self.instance.contract
But that doesn't work (it shows no errors but the selected attributes doesn't appear as selected). And furthermore, the following doesn't work either:
def __init__(self, *args, **kwargs):
super(ProfileForm, self).__init__(*args, **kwargs)
self.fields['contract'].initial = ['scholar', 'contract', 'freelance']
It has only worked as the first way, but with the problem that I don't know how to access to the attribute contract. Any ideas? Thanks in advance