Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango MultiValueField - How to pass choices to ChoiceField?
    primarykey
    data
    text
    <p>I have a multivaluefield with a charfield and choicefield. I need to pass choices to the choicefield constructor, however when I try to pass it into my custom multivaluefield I get an error <code>__init__()</code> got an unexpected keyword argument 'choices'. </p> <p>I know the rest of the code works because when I remove the choices keyword argument from <code>__init__</code> and super, the multivaluefield displays correctly but without any choices.</p> <p>This is how I setup my custom multivaluefield:</p> <pre><code>class InputAndChoice(object): def __init__(self, text_val='', choice_val=''): self.text_val=text_val self.choice_val=choice_val class InputAndChoiceWidget(widgets.MultiWidget): def __init__(self, attrs=None): widget = (widgets.TextInput(), widgets.Select() ) super(InputAndChoiceWidget, self).__init__(widget, attrs=attrs) def decompress(self,value): if value: return [value.text_val, value.choice_val] return [None, None] class InputAndChoiceField(forms.MultiValueField): widget = InputAndChoiceWidget def __init__(self, required=True, widget=None, label=None, initial=None, help_text=None, choices=None): field = ( fields.CharField(), fields.ChoiceField(choices=choices), ) super(InputAndChoiceField, self).__init__(fields=field, widget=widget, label=label, initial=initial, help_text=help_text, choices=choices) </code></pre> <p>And I call it like so:</p> <pre><code>input_and_choice = InputAndChoiceField(choices=[(1,'first'),(2,'second')]) </code></pre> <p>So how do I pass the choices to my ChoiceField field?</p> <p>Edit:</p> <p>I've tried stefanw's suggestion but still no luck. I've used logging.debug to print out the contents of InputAndChoiceField at the end of the init and self.fields[1].choices contains the correct values as per above however it doesnt display any choices in the browser.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload