在动态设置的MultipleChoiceField上验证,该字段最初为空?

时间:2011-08-25 14:54:03

标签: python ajax django validation

我的视图中有几种不同的形式。第一种形式具有填充多选字段的搜索字段,并且当用户在搜索字段中键入其查询时,发送AJAX调用以带来与查询匹配的所有记录。然后,用户从第一个多选字段中选择选项,然后单击“添加”将它们移动到另一个多选框

这样可以正常工作,但是当表单提交时,我会收到一条错误 “选择有效的选择.1不是可用的选择之一。” 我已经尝试在接收形式init之后设置选项,但这似乎不起作用。

我的表格:

class SiteCoordinatorForm(forms.ModelForm):
    selected_studies = forms.MultipleChoiceField(required = False)
    site = forms.ChoiceField(required = False)    
    studies = forms.MultipleChoiceField(required = False)
    study_search = forms.CharField(max_length = 50, required = False)

    def __init__(self, *args, **kwargs):
        super(SiteCoordinatorForm, self).__init__(*args, **kwargs)        
        if args:
            study_list = []
            query_dict = args[0]
            self.fields['selected_studies'].choices = [(int(x), x) for x in   query_dict.getlist('selected_studies')]

        self.fields['site'].choices = [(x.pk, "%s (%s)" % (x.primary_name, x.primary_number)) for x in Site.objects.all().order_by('primary_name')]

    class Meta:
        model = SiteCoordinator
        exclude = ('studies', 'site', 'selected_studies')

我的AJAX功能填充框:

def search_studies(request):
    return_data = {}
    studies = []
    make_query = lambda terms, fieldname: reduce(lambda x, y: x & Q(**{fieldname + '__icontains': y}), terms, Q())
    if 'search_text' in request.POST:
        terms = request.POST['search_text'].split()
        for rec in Study.objects.filter(make_query(terms, 'name')):
            studies.append({
                'study': {'id': rec.id, 'name': rec.name, 'number': rec.id}
            })

    response = {'status': 'success', 'count': len(studies), 'studies': studies}
    return HttpResponse(simplejson.dumps(response), mimetype="application/json")

填充MultiSelectBox的功能:

function show_results(data, status_code, request){
    recs = data.studies;
    var select_box = document.getElementById('id_studies');
    select_box.options.length = 0;

    for (var index = 0; index < recs.length; index ++){
        select_box.options[index] = new Option(recs[index].study.name,
                        recs[index].study.id,
                        false, false);
    }
}

然后JQuery移动选择:

$('#add').click(function() {
    $('#id_studies option:selected').remove().appendTo('#id_selected_studies');
    return false;

});

$('#remove').click(function() {  
    $('#id_selected_studies option:selected').remove().appendTo('#id_studies');
    return false;
});

2 个答案:

答案 0 :(得分:4)

很明显,我们不希望对MultipleChoiceField进行验证,但确实需要MultipleSelectWidget,因此解决方案只是将字段更改为

studies = forms.CharField(widget=forms.SelectMultiple)

并在

中进行自己的验证
def clean_studies(self):
    ...

答案 1 :(得分:0)

这是一个使用@AnuragUniyal提出的解决方案的例子,也回答了@ JohnLehmann的评论:

Routing.generate()

基本上我们将unicode字符串列表的字符串转换回应用class MyForm(forms.Form): new_tags = forms.CharField(required=False, widget=forms.SelectMultiple) def save(self, commit=True): instance = super(MyForm, self).save(commit=commit) for tag in eval(self.cleaned_data['new_tags']): models.Tag.objects.get_or_create(name=tag) return instance 的Python列表。