这是使用form_kwargs在Django 1.9中修复的.
我有一个看起来像这样的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)
Run Code Online (Sandbox Code Playgroud)
我用这样的方式称这个形式:
form = ServiceForm(affiliate=request.affiliate)
Run Code Online (Sandbox Code Playgroud)
request.affiliate登录用户在哪里.这按预期工作.
我的问题是我现在想把这个单一的表单变成一个formset.我无法弄清楚的是,在创建formset时,我如何将联盟信息传递给各个表单.根据文档制作一个formset,我需要做这样的事情:
ServiceFormSet = forms.formsets.formset_factory(ServiceForm, extra=3)
Run Code Online (Sandbox Code Playgroud)
然后我需要像这样创建它:
formset = ServiceFormSet()
Run Code Online (Sandbox Code Playgroud)
现在,我如何通过这种方式将affiliate = request.affiliate传递给单个表单?