Django多选字段验证

时间:2016-07-21 23:24:51

标签: python django select view

问题是我的表单类中有几个多选字段,他们无法在view.py中传递 is_valid 方法。

Forms.py

<%= f.select :consultant_id, options_for_select(Consultant.active.map{|s|[s.first_name, s.id]}, params[:consultant_id]), {}, class: 'form-control' %>

View.py

class SearchForm(forms.Form) : 
LIMIT_OPTIONS = (('5', '5'),
                ('10', '10'),
                ('15', '15'),
                ('20', '20'))
keyword = forms.CharField(max_length=50)    
limit = forms.MultipleChoiceField(widget=forms.Select, choices=LIMIT_OPTIONS)

如果我将class IndexView(View) : form_class = SearchForm template_name = 'web/index.html' def get(self, request) : form = self.form_class(None) return render(request, self.template_name, {'form':form}) def post (self, request) : form = self.form_class(request.POST) if form.is_valid(): url = '****' keyword = form.cleaned_data['keyword'] limit = form.cleaned_data['limit'] userupload = {'keyword': keyword, 'limit': limit} response = requests.post(url, json = userupload) return HttpResponse(response) return HttpResponse('<h1>Error</h1>') 更改为MultipleChoiceField,那么一切都很好......

我在互联网上找不到任何相关答案......

注意:我不使用任何数据库或模型(以防万一重要)

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

MultipleChoiceField的默认小部件是SelectMultiple

  

与Select类似,但允许多项选择:...

您已将表单中的内容更改为forms.Select。因此结果。

答案 1 :(得分:0)

因此,如果您希望form.py中有下拉选择字段,Widget - Select未通过验证(is_valid方法)

class SearchForm(forms.Form) : 
LIMIT_OPTIONS = (('5', '5'),
                ('10', '10'),
                ('15', '15'),
                ('20', '20'))
    limit = forms.MultipleChoiceField(widget=forms.Select, choices=LIMIT_OPTIONS)

只需将其更改为常规CharField并添加widget=forms.Select(choices=LIMIT_OPTIONS)

即可

示例:

class SearchForm(forms.Form) : 
LIMIT_OPTIONS = (('5', '5'),
                ('10', '10'),
                ('15', '15'),
                ('20', '20'))
    limit = forms.CharField(widget=forms.Select(choices=LIMIT_OPTIONS))