从没有实例的ModelForm中获取模型的属性(重写\uu init \uuu)

2024-04-24 06:41:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个MultipleChoiceField,为了显示以前在admin中选择的值,我必须重写ModelForm中的init方法。我有下面的类及其形式:

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)

使用initial['contract']=['scholar','contract','freelance']工作(这些值显示为选中),但我必须使用Profile中的属性contract来实现这一点。我知道您可以从属性为instance的ModelForm访问模型,但有一个问题:只有在调用init的本机方法之后,您才能访问instance。在这种情况下,我必须稍后再打给它,否则它对我不起作用。我已经试过以下方法:

def __init__(self, *args, **kwargs):
    super(ProfileForm, self).__init__(*args, **kwargs)
    self.fields['contract'].initial = self.instance.contract

但这不起作用(它不显示错误,但选定的属性不会显示为选定的)。而且,以下也不起作用:

def __init__(self, *args, **kwargs):
    super(ProfileForm, self).__init__(*args, **kwargs)
    self.fields['contract'].initial = ['scholar', 'contract', 'freelance']

它只是第一种方式,但问题是我不知道如何访问属性契约。 有什么想法吗?提前谢谢


Tags: 方法selfinitmodelsdefargsprofilekwargs