【问题标题】:django 1.3 forms validation using clean method to retrieve getlistdjango 1.3 表单验证使用干净的方法来检索getlist
【发布时间】:2011-09-02 16:07:47
【问题描述】:

我有一个带有复选框的表单,该表单运行良好,在我看来,我可以使用 request.POST.getlist('list') 来检索值列表。

目前我正在尝试在 clean 方法中进行一些表单验证,当我尝试使用 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

【问题讨论】:

  • 我刚刚添加了代码和一些尝试打印的 cmets

标签: python django


【解决方案1】:

首先,这里有一些基本的 Python 错误。几乎不需要访问双下划线函数——它们是内部实现细节。请始终使用普通的len() 函数。而且,永远不要使用is 进行比较:它是用于标识的,因此只能用于您知道具有相同标识的事物,这基本上只是意味着None。所以你的代码应该是:

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

等等

其次,我不明白你为什么认为list 中可能有不止一个“元素”。您已将其定义为 CharField,它是包含许多字符的单个字段。您的 len 正在测试输入该字段的字符数,而不是字段数,但是您认为您已经定义了它们。

【讨论】:

  • 感谢有关使用 len() 的提示,随着代码的增长,这肯定有助于保持适当的标准。至于列表,您可以在 Posting_Wizard 类中看到,正在修改它显示 form.fields['list']=forms.CharField(widget=forms.Chec...等的字段,修改后的字段应该返回列表复选框。我无法访问,但我可以从 request.POST.getlist('list') 访问
猜你喜欢
  • 2016-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-11
  • 2018-02-08
  • 2023-03-12
  • 1970-01-01
相关资源
最近更新 更多