动态形式抱怨"步骤"作为意外的关键字参数

时间:2016-10-24 23:03:05

标签: django django-forms django-views

我的表单允许多个"步骤"在表格中提交。通过JavaScript按下表单上的按钮添加步骤。

问题是django形式和验证:

class TaskForm(forms.Form):
    task_name = forms.CharField
    step_number = forms.IntegerField(widget=forms.HiddenInput())

    def __init__(self, *args, **kwargs):
        step_fields = kwargs.get('step_number', 0)
        super(TaskForm, self).__init__(*args, **kwargs)
        self.fields['step_number'].initial = step_fields

        for index in range(int(step_fields)):
            self.fields['step_field_{index}'.format(index=index)] = forms.CharField()

这将创建表单,其中任务名称是首次加载页面时的唯一输入字段。这是预期的。

我通过浏览器将步骤添加到我的任务中,这样可以正常工作并且隐藏字段正在递增。

然后我提交,但我收到错误:

  在' task-app / create-task.html'

上的

TypeError      

__ init __()得到了一个意想不到的关键字参数' step_number'

显然,关键字参数来自views.py:

def add_task(request):
    if request.user.is_authenticated():
        if request.method == 'POST':
            form = TaskForm(request.POST, step_number=request.POST.get('step_number'))
            if form.is_valid():
                # do something with the form
                create_task(form)
                messages.success(request, "The task form was valid")
                return redirect('task-app:homepage')
            else:
                messages.warning(request, "The form is not valid")
                return render(request, 'task-app/create-task.html', {'form':form})
        else:
            form = TaskForm()
            return render(request, 'task-app/create-task.html', {'form':form})

1 个答案:

答案 0 :(得分:1)

在你打电话给TaskForm的超级初始化之前,你是否忘记从kwargs弹出step_number

你应该pop来自kwargs而不是get,否则表单会抛出一个像你一样的异常,因为super().__init__不期望额外的参数。< / p>

class TaskForm(forms.Form):
    task_name = forms.CharField()
    step_number = forms.IntegerField(widget=forms.HiddenInput())

    def __init__(self, *args, **kwargs):
        step_fields = kwargs.pop('step_number', 0)
        super(TaskForm, self).__init__(*args, **kwargs)
        self.fields['step_number'].initial = step_fields

        for index in range(int(step_fields)):
            self.fields['step_field_{index}'.format(index=index)] = forms.CharField()