2

I have a class like this.

class AddNoteForm(forms.Form):
    def __init__(self, test_values, *args):
        self.custom_choices = test_values
        super(AddNoteForm, self).__init__()
        self.fields['choices'] = forms.ModelMultipleChoiceField(label='Test Choices', choices=self.custom_choices)

I'd like to pass this tuple during class creation.

test_values = (
    ('name1', 'value1'), 
    ('name2', 'value2'),
    ('name3', 'value3'),
)

form = AddNoteForm(test_values)

But whenever I do so, I get a __init__() takes at least 2 arguments (2 given) error. I'm also using python 2.7 (and Django 1.8).

I look at the variables in the debug page and self.custom_choices contain the right values (test_values that I passed into the function).

Any ideas?

1
  • What is the method signature for forms.Form, from which AddNoteForm inherits? Commented Jul 24, 2015 at 4:52

1 Answer 1

1

ModelMultipleChoiceField is expecting a queryset as its first parameter (following self). What you want here is a regular MultipleChoiceField.

I also threw in the passing of args/kwargs to the superclass init, which is a good practice since forms can take a lot of useful parameters, such as 'initial', that you might want to use some time, and then it'll drive you nuts when it doesn't work...

class AddNoteForm(forms.Form):
    def __init__(self, test_values, *args, **kwargs):
        self.custom_choices = test_values
        super(AddNoteForm, self).__init__(*args, **kwargs)
        self.fields['choices'] = forms.MultipleChoiceField(
          label='Test Choices',
          choices=self.custom_choices
        )
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.