Django – Custom Queryset with a Formset

My goal was to apply a custom queryset to a foreign key field. When the field is in a single model form, it was pretty clear to me how to proceed. However, when the field in question is part of a ModelFormset, I wasn’t seeing the way. Oddly enough, it came to me right before bed one night – iterate through the forms in the formset to apply the queryset to each one. Here’s how I handled each case.

In this application, there is a one-to-many relationship between Event and Rsvp, and a one-to-many between Rsvp and Seat

(snippet from

    ## build the querysets
    event_queryset = Event.futures.filter(institution=inst_id)
    person_queryset = Person.objects.filter(institution=inst_id)    

    ## create the formset
    SeatFormSet    = inlineformset_factory(Rsvp, Seat, form=SeatForm, can_delete=True, extra=3)

    ## instantiate the form and formset
    rsvpform      = RsvpForm(instance=rsvp)
    seatformset    = SeatFormSet(instance=rsvp)

    ## Apply the queryset to the master form
    rsvpform.fields['event'].queryset = event_queryset

    ## Apply the queryset to each form in the formset
    for form in seatformset.forms:
        form.fields['person'].queryset = person_queryset

It’s important to note that the querysets must be applied each time the form and formset are instantiated in your view code in order for the validation to work correctly.

In the for statement, I first tried iterating on the formset itself, but I was told that it was not iterable. A little perusal of the Django code for formsets showed me that the forms variable in the model was the object to use instead.

I’d love to hear your comments on this technique.

Phone Numbers From Around the World

What do you do with phone numbers?

I’ve used some different tricks to validate phone numbers in the North American format (999-999-9999), but I’ve learned that we also have invitees from Europe and other locales.  The problem I have, and I think it is a common problem, is that I need to be able to accept all possible phone number formats while attempting to validate the format used.  The goal of course is to minimize entry mistakes by the users.

I would love to hear your thoughts in the comments.