【问题标题】:Dynamic Select Choices in Admin管理员中的动态选择选项
【发布时间】:2014-07-29 13:48:34
【问题描述】:

我想创建一个级联父/子选择器,其中子选项基于父选择。选择来自预定义的变量/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 中获取“父”值,以便可以使用它来填充子选项吗?有什么想法吗?

【问题讨论】:

  • 请重命名主题以将“动态”与“级联”交换。您在初始化时获得 静态级联 选项,而不是在运行中选择表单上的父选项时加载新的 动态选项集(例如,来自另一个模型或查询集) -时间。主题名称混淆。

标签: python django django-admin cascadingdropdown


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-17
    • 2017-08-16
    • 1970-01-01
    • 2016-07-18
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多