Django Passing Custom Form Parameters to Formset

I would use functools.partial and functools.wraps: from functools import partial, wraps from django.forms.formsets import formset_factory ServiceFormSet = formset_factory(wraps(ServiceForm)(partial(ServiceForm, affiliate=request.affiliate)), extra=3) I think this is the cleanest approach, and doesn’t affect ServiceForm in any way (i.e. by making it difficult to subclass).

dynamically add field to a form

Your form would have to be constructed based on some variables passed to it from your POST (or blindly check for attributes). The form itself is constructed every time the view is reloaded, errors or not, so the HTML needs to contain information about how many fields there are to construct the correct amount of … Read more

Creating a dynamic choice field

you can filter the waypoints by passing the user to the form init class waypointForm(forms.Form): def __init__(self, user, *args, **kwargs): super(waypointForm, self).__init__(*args, **kwargs) self.fields[‘waypoints’] = forms.ChoiceField( choices=[(o.id, str(o)) for o in Waypoint.objects.filter(user=user)] ) from your view while initiating the form pass the user form = waypointForm(user) in case of model form class waypointForm(forms.ModelForm): def __init__(self, … Read more

How do I filter ForeignKey choices in a Django ModelForm?

ForeignKey is represented by django.forms.ModelChoiceField, which is a ChoiceField whose choices are a model QuerySet. See the reference for ModelChoiceField. So, provide a QuerySet to the field’s queryset attribute. Depends on how your form is built. If you build an explicit form, you’ll have fields named directly. form.rate.queryset = Rate.objects.filter(company_id=the_company.id) If you take the default … Read more