擅长:python、mysql、java
<p>我将在一个函数中动态构建表单类,以便它可以通过闭包访问分支:</p>
<pre><code>def make_service_form(affiliate):
class ServiceForm(forms.Form):
option = forms.ModelChoiceField(
queryset=ServiceOption.objects.filter(affiliate=affiliate))
rate = forms.DecimalField(widget=custom_widgets.SmallField())
units = forms.IntegerField(min_value=1,
widget=custom_widgets.SmallField())
return ServiceForm
</code></pre>
<p>另外,您不必重写选项字段中的queryset。缺点是子类化有点古怪。(任何子类都必须以类似的方式创建。)</p>
<p><strong>编辑:</strong></p>
<p>作为对注释的响应,可以在任何使用类名的位置调用此函数:</p>
<pre><code>def view(request):
affiliate = get_object_or_404(id=request.GET.get('id'))
formset_cls = formset_factory(make_service_form(affiliate))
formset = formset_cls(request.POST)
...
</code></pre>