管理界面的动态选择项
我想创建一个级联的父子选择器,也就是说,子选项是根据父选项来决定的。选项是从预先定义的变量或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 个回答
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