使用clean方法在Django 1.3中进行表单验证以获取getlist

0 投票
1 回答
1032 浏览
提问于 2025-04-17 01:16

我有一个包含复选框的表单,这个表单运行得很好。在我看来,我可以用 request.POST.getlist('list') 来获取值的列表。

现在我正在尝试在清理方法里面做一些表单验证,当我试图使用 self.cleaned_data['list'] 时,我只得到了最后一个值,无法获取到所有的项目列表。

有没有什么办法可以做到这一点呢?

forms.py

class SelectList_Form(forms.Form):
    list = forms.CharField(required=False)


    def clean(self):
        super(SelectList_Form, self).clean()
        cleaned_data = self.cleaned_data

        try:
            # TODO: list validation
            if cleaned_data['list'].__len__() is 0:
                raise forms.ValidationError(_('Must select at least one of the lists below'),)

            if cleaned_data['list'].__len__() > 1:
                try:
                    # In here when i print list it only shows me the last value. It doesn't show me the list of values when the box is checked
                    print cleaned_data['list']



                except Main.DoesNotExist:
                    raise Http404

        except forms.ValidationError:
            raise

class Posting_Wizard(FormWizard):

    def render_template(self, request, form, previous_fields, step, context=None):
        if step == 0:
            obj = MainI18n.objects.filter(main__is_active=True, language=request.LANGUAGE_CODE).\
                    exclude(main__parent=None).order_by('main__parent').select_related(depth=1)
            category_choices=dict(['%s,%s' % (i.main.slug, i.main.parent.slug), '%s - %s' % (i.main.parent,i.label)] for i in obj)

            form.fields['categories'] = forms.CharField(widget=forms.RadioSelect(choices=category_choices.items()))


    if step == 1:
        category = request.POST.get('0-categories')

        pobj  = Main.objects.filter(slug=category.split(',')[1], parent=None).get()
        cobj =  Main.objects.filter(slug=category.split(',')[0], parent=pobj.id).get()
        lobj =  ListI18n.objects.filter(list__is_active=True, language=request.LANGUAGE_CODE, list__main__slug=category.split(',')[0], list__main__parent=pobj.id).select_related()

        list_choices = dict([i.id, i.title] for i in lobj)

        if cobj.mainproperties.relation == 'M':
           # Here i generate the checkboxes
            form.fields['list']=forms.CharField(widget=forms.CheckboxSelectMultiple(choices=list_choices.items()),label="Pick the list",)
        else:
            form.fields['list']=forms.CharField(widget=forms.RadioSelect(choices=list_choices.items()),label="Pick the list",)


    return super(Posting_Wizard, self).render_template(request, form, previous_fields, step, context)


def done(self, request, form_list):
    return HttpResponseRedirect(reverse('accounts-registration-wizard-done'))

def get_template(self, step):
    return 'listing/post/wizard/wizard_%s.html' % step

1 个回答

0

首先,这里有一些基本的Python错误。几乎没有必要去访问那些双下划线开头的函数——它们是内部实现的细节。你应该始终使用普通的 len() 函数。还有,比较的时候不要用 is:它是用来判断身份的,所以只应该用在你确定是同一个东西的情况下,基本上就是 None。所以你的代码应该写成:

if len(cleaned_data['list']) == 0:

等等。

其次,我不明白你为什么会认为 list 中会有多个“元素”。你把它定义为一个CharField,这其实是一个只包含多个字符的单一字段。你的 len 是在测试这个字段中输入的字符数量,而不是你认为定义的字段数量。

撰写回答