django自定义表单获取__init __()最多需要2个参数(3个给定)错误

时间:2014-08-11 18:37:04

标签: python django django-forms

我有以下表格:

class QuestionForm(forms.Form):
    options = forms.ModelMultipleChoiceField(queryset=Option.objects.none(), 
                                    widget=forms.RadioSelect)
    def __init__(self, question_id=None):
        if question_id:
            super(QuestionForm, self).__init__()
            question = Question.objects.get(pk=question_id)

            self.fields['options'].queryset = Option.objects.filter(question = question) 

在我看来,我正在调用表单来获取用户在帖子中选择的内容:

if request.method == "POST":
        form = QuestionForm(request.POST, question.id)
        if form.is_valid():
            print form

然后我收到以下错误:

__init__() takes at most 2 arguments (3 given)

对于这一行:form = QuestionForm(request.POST, question.id)

2 个答案:

答案 0 :(得分:2)

错误正是它所说的:您的QuestionForm.__init__只接受两个参数(selfquestion_id),但是你给它三个(self(总是这样)给予实例方法),request.POSTquestion.id。您的__init__方法需要采用另一个参数来工作,例如:

def __init__(self, method, question_id):

答案 1 :(得分:0)

def __init__(self, question_id=None, *args, **kwargs):
    super(QuestionForm, self).__init__(*args, **kwargs)

现在它适用于所有情况,而不仅仅适用于您的特定形式。