问题描述
我有一个Django窗体,如下所示:
I have a Django Form that looks like this:
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)
我把这个表单称为这样的:
I call this form with something like this:
form = ServiceForm(affiliate=request.affiliate)
其中 request.affiliate
是登录用户。我的问题是,我现在想将这个单一的表单变成一个表单集。
Where request.affiliate
is the logged in user. This works as intended.
我无法想像的是,在创建表单集时,我可以如何将会员信息传递给各个表单。根据文档要做一个表单,我需要这样做:
My problem is that I now want to turn this single form into a formset. What I can't figure out is how I can pass the affiliate information to the individual forms when creating the formset. According to the docs to make a formset out of this I need to do something like this:
ServiceFormSet = forms.formsets.formset_factory(ServiceForm, extra=3)
然后我需要像这样创建它:
And then I need to create it like this:
formset = ServiceFormSet()
现在我如何以这种方式通过affiliate = request.affiliate到个人表单?
Now how can I pass affiliate=request.affiliate to the individual forms this way?
推荐答案
我会使用 functools.partial 和:
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认为这是最干净的方法,并不会以任何方式影响ServiceForm(即通过使其难以进行子类化)。
I think this is the cleanest approach, and doesn't affect ServiceForm in any way (i.e. by making it difficult to subclass).
这篇关于Django将自定义表单参数传递给Formset的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!