Django將自定義表單參數傳遞給Formset這是使用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)我用這樣的方式稱這個形式:form = ServiceForm(affiliate=request.affiliate)request.affiliate登錄用戶在哪里。這按預期工作。我的問題是我現在想把這個單一的表單變成一個formset。我無法弄清楚的是,在創建formset時,我如何將聯盟信息傳遞給各個表單。根據文檔制作一個formset,我需要做這樣的事情:ServiceFormSet = forms.formsets.formset_factory(ServiceForm, extra=3)然后我需要像這樣創建它:formset = ServiceFormSet()現在,我如何通過這種方式將affiliate = request.affiliate傳遞給單個表單?
Django將自定義表單參數傳遞給Formset
慕運維8079593
2019-08-06 14:42:56