Again a fairly generic task with forms that seems to be tricky. I'm trying to put together a bunch of custom forms, all different instances of the same form class constructed with different args, one for each entry in a given model.
For example, this custom form lets the user tick a checkbox if they've been to a destination, and select (multiple) activites they've done whilst there:
class VisitorDestinationForm(Form):
def __init__(self, visitor, destination, *args, **kwargs):
super(VisitorForm, self).__init__(*args, **kwargs)
visitorDestinations = visitor.destinations.all()
self.fields[destination.destination] = forms.BooleanField()
self.fields[destination.destination].initial = destination in visitorDestinations
And I would like to make a formset with one of these forms for each destination in my Destination
queryset. (I can handle the visitor
arg using curry, as suggested here)
The accepted answer to this question implies that modelformset_factory
can take a simply a (custom) form and a (unrelated) queryset.
But if I try that I get an error:I can't use modelformset_factory
, because the VisitorDestinationForm
are not modelforms for the model I get my queryset (they are related though, and they should take a model instance in the constructor). This is confirmed if I look into the code (django 1.3)
It looks like django only handles 3 cases:
- formset_factory: a set of forms of the same type constructed with the same params
- modelformset_factory: a set of model forms for a queryset from that model
- inlineformset_factory: a set of forms for related queryset linked via FK (NOT M2M)
But there seems to be nothing if you want to put together a list of custom forms that are initialised from a list of objects. I'm surprised about this, I thought it would be quite a common situation
Will I have to write my own custom formset_factory, by overriding the _construct_forms
method in BaseFormSet
? Or should I simply handle the bunch of forms separately in my view, and is there something to watch out for in this case (I heard validation can be tricky)?