管理员中的动态选择选项

时间:2014-07-29 13:48:34

标签: python django django-admin cascadingdropdown

我想创建一个级联的Parent / Child选择器,其中子选项基于父选项。选择来自预定义的变量/ json。用户需要选择父选项才能获得响应子选项。因此,默认情况下,孩子没有选择权。

我实现了Ajax以填充管理表单中的子选项,但是当保存模型时,子选项将恢复为初始状态,而不会填充任何选项。

#choices
PARENT = {
    ('1','Parent 1'),
    ('2','Parent 2'),
    ('3', 'Parent 3'),
}
CHILD_CHOICES = {
    '1' : (("c1-opt1","Option 1-1"),("c1-opt2","Child option 1-2"),("c1-opt3","Child option 1-3")),
    '2' : (("c2-opt1","Option 2-1"),("c2-opt2","Child option 2-2"),("c2-opt3","Child option 2-3")),
    '3' : (("c3-opt1","Option 3-1"),("c2-opt3","Child option 3-2"),("c2-opt3","Child option 3-3"))
}
#model.py
class Relation(models.Model)
parent = models.CharField(max_length=4,choices=Parent,blank=True)
child = models.CharField(max_length=200)

我知道我可以自定义“孩子”。 admin.py中的字段,但我不知道根据页面加载中保存的模型父字段填充选项。

#admin.py
class Cascadingform(forms.ModelForm):
    class Meta:
        model = Relation

    def __init__(self,  *args, **kwargs):
    super(Cascadingform, self).__init__(*args, **kwargs)
    if(self.parent): #not sure how to get the parent value here
        self.fields['child'] = forms.Select(choices=CHILD_CHOICES[self.parent])#  populated the choice based on the dict above. 

问题是我可以得到父母的帮助吗? init 中的值,以便我可以使用它来填充子选项?有什么想法吗?

1 个答案:

答案 0 :(得分:1)

经过几天的谷歌搜索,这是我的解决方案:

def getFieldChoices(parent):
    CHILD_CHOICES = {
'1' : (("c1-opt1","Option 1-1"),("c1-opt2","Child option 1-2"),("c1-opt3","Child option 1-3")),
'2' : (("c2-opt1","Option 2-1"),("c2-opt2","Child option 2-2"),("c2-opt3","Child option 2-3")),
'3' : (("c3-opt1","Option 3-1"),("c2-opt3","Child option 3-2"),("c2-opt3","Child option 3-3"))}
    L = list()
    data = CHILD_CHOICES.get(parent, None)
    if data:
        L = [[x, x] for x in data]    
    return L


#admin.py
class Cascadingform(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(Cascadingform, self).__init__(*args,**kwargs)

        if (self.instance.parent):
            self.fields['child'] = forms.CharField(widget=forms.Select(attrs={'class':'childclass'},choices=getFieldChoices(self.instance.parent))
                            )
        else:
            self.fields['child'] = forms.CharField(widget=forms.Select(attrs={'class':'childclass'},choices=[('','Select Parent First'),])
                            )
    class Meta:
        model = Relation