2017-09-14 60 views
0

我正在处理需要自定义选择选项属性的自定义需求。我的下拉菜单中会显示选项列表,其中一些选项应该按照特定条件显示为禁用。如何自定义窗体的属性。在Django中选择选项

List of options along with disabled options

我曾尝试定制Select widget attributes通过传递disabled = disabled的。但是这会禁用整个下拉菜单。通过查看django 1.11.5的代码,似乎应用于Select的属性将应用于其选项。

任何人都可以请建议如何实现此功能?

谢谢

回答

0

我觉得你可以子类django.forms.widgets.Select小部件,传递新的参数disabled_choices__init__功能和覆盖create_option方法是这样的:

class MySelect(Select): 

    def __init__(self, attrs=None, choices=(), disabled_choices=()): 
     super(Select, self).__init__(attrs, choices=choices) 
     # disabled_choices is a list of disabled values 
     self.disabled_choices = disabled_choices 

    def create_option(self, name, value, label, selected, index, subindex=None, attrs=None): 
     option = super(Select, self).create_option(name, value, label, selected, index, subindex, attrs) 
     if value in disabled_choices: 
      option['attrs']['disabled'] = True 
     return option 

希望这有助于。

+0

非常感谢。这真的是一个很好的帮助。我可以在做一些小改动后使用它:-) –