gpt4 book ai didi

python - 如何自定义表单的属性。在 Django 中选择选项

转载 作者:太空宇宙 更新时间:2023-11-03 14:46:22 25 4
gpt4 key购买 nike

我正在处理一个自定义需求,该需求要求自定义选择选项属性。我的下拉列表将显示选项列表,其中一些选项应根据某些条件显示为禁用。

List of options along with disabled options

我尝试通过传递disabled=disabled来自定义选择小部件属性。但这会禁用整个下拉列表。通过查看 django 1.11.5 的代码,似乎应用于 Select 的属性将应用于其选项。

有人可以建议如何实现此功能吗?

谢谢

最佳答案

我认为您可以对 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 self.disabled_choices:
option['attrs']['disabled'] = True
return option

希望这有帮助。

关于python - 如何自定义表单的属性。在 Django 中选择选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46213193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com