我有一个看起来像这样的Django表单:
class ServiceForm(forms.Form): option = forms.ModelChoiceField(queryset=ServiceOption.objects.none()) rate = forms.DecimalField(widget=custom_widgets.SmallField()) units = forms.IntegerField(min_value=1, widget=custom_widgets.SmallField()) def __init__(self, *args, **kwargs): affiliate = kwargs.pop('affiliate') super(ServiceForm, self).__init__(*args, **kwargs) self.fields["option"].queryset = ServiceOption.objects.filter(affiliate=affiliate)
我称这种形式的东西是这样的:
form = ServiceForm(affiliate=request.affiliate)
request.affiliate登录用户在哪里。这按预期工作。
request.affiliate
我的问题是我现在想将此单一表单转换为表单集。我不知道的是在创建表单集时如何将会员信息传递给各个表单。根据文档来制作一个表单集,我需要做这样的事情:
ServiceFormSet = forms.formsets.formset_factory(ServiceForm, extra=3)
然后我需要这样创建它:
formset = ServiceFormSet()
现在,如何以这种方式将affiliate = request.affiliate传递给各个表单?
affiliate = request.affiliate
我会用functools.partial和functools.wraps:
functools.partial
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)
我认为这是最干净的方法,并且不会以任何方式影响ServiceForm(即,使子类难以继承)。
ServiceForm