Django动态表单ValidationErorr

时间:2010-08-31 07:43:12

标签: django jquery django-forms

我正在尝试修改admin ModelMultipleChoiceField,因此它会动态加载数据。

因为我想动态加载数据,所以在创建表单实例时,ModelMultipleChoiceField的查询集为空,因此在进行表单验证时,django会抱怨选项无效,因为它们在查询集中找不到。

有什么方法吗?

FORM:
class FormName(forms.ModelForm):
    dinamic_field = forms.ModelMultipleChoiceField(Entry.objects.none(),widget=
            widgets.FilteredSelectMultiple("", False))

    class Meta:
        model = ModelName
        fields = ('dinamic_field',)

    class Media:
        js = ('jquery.js', 'dinamic_field.js')

查看:

def add(request):
    if request.method == 'POST':
        form = FormName(request.POST)
        if request.is_ajax():
             obj = Packages.objects.get(id = form.data['package'])
            form.fields['dinamic_field'].queryset = Entry.objects.filter(test__in =obj.all())
            return HttpResponse(form['dinamic_field'])
        if form.is_valid():
            job = form.save()
            return HttpResponseRedirect('../../')
    else:
        form = FormName()

    return return render_to_response('/template_name', {'form': 'form'})

1 个答案:

答案 0 :(得分:0)

您是否尝试覆盖表单的__init__()方法并为字段设置queryset?类似的东西:

class JobForm(forms.ModelForm):
    dynamic_field = forms.ModelMultipleChoiceField(Entry.objects.none(),widget=
            widgets.FilteredSelectMultiple("", False))

    def __init__(self, *args, **kwargs):
        super(JobForm, self).__init__(*args, **kwargs)
        self.dynamic_field.queryset = Entry.objects.<etc>