【问题标题】:Django how to pass choices list to a custom select widgetDjango如何将选择列表传递给自定义选择小部件
【发布时间】:2019-01-08 14:52:40
【问题描述】:

我需要覆盖选择小部件。

class TooltipSelectWidget(Select) :

    def __init__(self, *args, **kwargs) :
        super().__init__(*args, **kwargs)

然后我把它称为一个表格。但我在文档中没有看到如何将选择列表传递给这个自定义小部件。

【问题讨论】:

    标签: python django django-forms django-widget


    【解决方案1】:

    在您的代码中,调用超类初始化器后,设置选项如下:

    class TooltipSelectWidget(Select) :
    
        def __init__(self, *args, **kwargs) :
            super().__init__(*args, **kwargs)
            self.choices = []  # List of 2-tuple values
    

    如果您查看Select 类(自定义小部件的基类)的__init__ 的代码,您可以直观地了解为什么这是解决方案:

    class Select(Widget):
        allow_multiple_selected = False
    
        def __init__(self, attrs=None, choices=()):
            super(Select, self).__init__(attrs)
            # choices can be any iterable, but we may need to render this widget
            # multiple times. Thus, collapse it into a list so it can be consumed
            # more than once.
            self.choices = list(choices)
    

    更好的方法是在您的

    中默认包含您的自定义选项
    class TooltipSelectWidget(Select) :
    
       CUSTOM_CHOICES = ()  # Modify at will. 
    
        def __init__(self, attrs=None, choices=CUSTOM_CHOICES) :
            super().__init__(attrs=attrs, choices=choices)
    

    【讨论】:

    • 基于您出色的解决方案,我建议大家查看django source 获取小部件。这完成了你的解释。
    【解决方案2】:

    如果 choix 包含可供选择的元组列表,那么下面的代码就可以完成这项工作:

    form.fields[name] = ChoiceField (widget = TooltipSelectWidget (attrs = attrs, choices = choix) choices = choix)
    

    诀窍是选择列表需要重复,一次用于小部件,一次用于选择字段)

    【讨论】:

      【解决方案3】:

      将此添加到表单初始化中:

      def __init__(self, *args, **kwargs):
          super().__init__(*args, **kwargs)
          CHOICES = [()]
          self.fields['choice_field'].choices = CHOICES
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-12-09
        • 1970-01-01
        • 2013-02-24
        • 1970-01-01
        • 2013-09-13
        • 2019-11-02
        • 2020-04-21
        • 2022-12-05
        相关资源
        最近更新 更多