0

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

bcap
  • 500
  • 5
  • 14
  • Why do you think you only have the instance after you've called `super`? If it was passed on instantiation, it'll be in `kwargs`. – Daniel Roseman Jul 15 '15 at 14:24
  • I have tried with `instance = kwargs.get('instance',{})` and then `initial['contract'] = instance.contract` but has no effect (no error but not displaying selected options) @DanielRoseman – bcap Jul 15 '15 at 14:47

0 Answers0