is_valid总是为假(Django)

时间:2011-05-16 09:48:17

标签: django

我的动态字段有以下形式:

1 )在 models.py 中,我想将值传递给要查询的表单

class InsertValuesForm(forms.Form):
    def __init__(self, idfield, *args, **kwargs):           

        super(InsertValuesForm, self).__init__(*args, **kwargs)

        for f in Parameter.objects.filter(id=idfield):          

            if Part.objects.get(parameter=f.parameter_name).isfunction:
                self.fields.update({
                            f.parameter_name) : forms.CharField(widget=forms.TextInput() )})

1) views.py

def something(request)
#......
                idfield = request.GET.get('feid','0')

                form = InsertValuesForm(request.POST,idfield)

                if request.method == 'POST':

                    if form.is_valid():

                       #some code

                else:

                    form = InsertValuesForm(idfield)

                return render_to_response('fuzz/configuration.html', {
                'form': form,
            },context_instance=RequestContext(request))

在第一种情况下,我能够在for循环中显示动态字段。但是,在填写所有字段并提交(POST)之后,表单将这个错误抛给了我:

int()参数必须是字符串或数字,而不是'QueryDict'。我以为是导致错误的request.POST。 在对这个问题进行一些研究后,有类似的解决方案:

http://groups.google.com/group/django-users/browse_thread/thread/ddefd76324ffe6cd http://groups.google.com/group/django-users/browse_thread/thread/495a917396b20b37/c430d71a31204e5d#c430d71a31204e5d

2) models.py

class InsertValuesForm(forms.Form):
    def __init__(self, *args, **kwargs):

        idfield = kwargs.pop('idfield', False)

        super(InsertValuesForm, self).__init__(*args, **kwargs)

        for f in Parameter.objects.filter(id=idfield):          

            if Part.objects.get(parameter=f.parameter_name).isfunction:
                self.fields.update({
                            f.parameter_name) : forms.CharField(widget=forms.TextInput() )})

以下的views.py片段(与数字1相同)

def something(request)
#......
                idfield = request.GET.get('feid','0')

                form = InsertValuesForm(request.POST,idfield)

                if request.method == 'POST':

                    if form.is_valid():

                       #some code

                else:

                    form = InsertValuesForm(idfield)

                return render_to_response('fuzz/configuration.html', {
                'form': form,
            },context_instance=RequestContext(request))

现在上面的代码甚至没有显示动态文本框,只显示为空白页面。感谢是否有人可以阐明

如何显示这些动态文本框,同时, 通过request.POST获取这些文本框的值,并使表单验证。感谢

1 个答案:

答案 0 :(得分:1)

您已更改表单__init__的签名,以便第一个位置参数为idfield。不要这样做,因为现在当您使用form = InsertValuesForm(request.POST,idfield)实例化它时,它将第一个参数设为idfield,而不是request.POST

相反,定义如下方法:

 def __init__(self, *args, **kwargs):
      idfield = kwargs.pop('idfield', None)
      ...etc...

并使用关键字arg:

对其进行实例化
form = InsertValuesForm(request.POST, idfield=idfield)