Darwin Tech
Darwin Tech

Reputation: 18929

Django validating empty ModelChoice form field

I have a form:

class ProjectInfoForm(forms.Form):
    module = forms.ModelChoiceField(
        queryset=Module.objects.all(),
    )
    piece = forms.ModelChoiceField(
        queryset=Piece.objects.all(),
        required=False,
    )

The second field is populated with option from the first using ajax. However, instantiating it like this is not very efficient as it means the second field is populated on page load uneccessarily (not to mention populates the field before it should).

So I tried changing it to:

    ...
    piece = forms.ModelChoiceField(
        queryset=Piece.objects.none(),
        required=False,
    )

I get the desired result but of course the form does not validate has it has no choices to check against.

Is there some way I can validate the form without populating it or even better validate the two fields together as related models?

Any help much appreciated.

Upvotes: 0

Views: 122

Answers (1)

Thomas Orozco
Thomas Orozco

Reputation: 55293

I think the easier way is just to roll your own. You'll just need:

  1. A ChoiceField. Using coerce will let you transform IDs into objects transparently
  2. A view that you AJAX component can query to retrieve the list of valid Pieces for a given Module.
  3. A server-side validation method that checks that the Module and the Piece correspond

Upvotes: 1

Related Questions