views:

30

answers:

1

I'm trying to modify the 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'})
A: 

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>
Manoj Govindan
you said 'save()' method and overwritten the constructor
John Retallack
I've tring overriding the constructor with an optional argument but it doesn't work, something like this : def __init__(self, obj=False, *args, **kwrds): super(FormName, self).__init__(*args, **kwrds) self.fields['dynamic_field'].widget = widgets.FilteredSelectMultiple("", False) self.fields['dynamic_field'].queryset = Entry.objects.none() if obj: self.fields[dynamic_field'].queryset = Entry.objects.filter(test__in =obj.all())
John Retallack
@John: my mistake. Corrected.
Manoj Govindan