piscvau
piscvau

Reputation: 21

Django how to pass choices list to a custom select widget

I need to override select widget.

class TooltipSelectWidget(Select) :

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

Then I call it in a form. But I do not see in the docs how to pass the choices list to this customed widget.

Upvotes: 0

Views: 1963

Answers (3)

Raydel Miranda
Raydel Miranda

Reputation: 14360

in your code, after call the super class initializer, set the choices as below:

class TooltipSelectWidget(Select) :

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

If you look at the code of the __init__ of the Select class (Base class for your custom widget) you can get intuition about why this is the solution:

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)

A better approach is to have your custom choices by default in your

class TooltipSelectWidget(Select) :

   CUSTOM_CHOICES = ()  # Modify at will. 

    def __init__(self, attrs=None, choices=CUSTOM_CHOICES) :
        super().__init__(attrs=attrs, choices=choices)

Upvotes: 1

Atley Varghese
Atley Varghese

Reputation: 576

Add this to form init:

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

Upvotes: 0

piscvau
piscvau

Reputation: 21

If choix contains the list of tuples for choices, then the code below does the job:

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

The trick is that the choices list need to be repeated, once for the widget and once for the choicefield)

Upvotes: 0

Related Questions