开发者

Django dynamic form ValidationErorr

I'm trying to modify the开发者_StackOverflow社区 admin ModelMultipleChoiceField so it does load data dynamically.

Because I want to load data dynamically the queryset for ModelMultipleChoiceField is empty when creating an instance of the form, for that reason when doing form validation django complains that the choices aren't valid because they can't be found in the queryset.

Is there any way around this ?

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')

VIEW:

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'})


Have you tried overriding your form's __init__() method and setting the queryset for the field? Something like:

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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜