2016-07-25 1 views
2

1.9에서 formset_factory에 대해 form_kwargsfeature을 새로 입력하면 formset의 특정 필드에 대한 쿼리 세트를 설정할 수 있습니다. 내 질문은 inlineformset_factory에 대해 어떻게 동일한 결과를 얻을 수 있습니까? 다음을 수행인라인 formset에 새 form_kwargs를 사용하는 방법은 무엇입니까?

작동하지 않습니다 : 내가 얻을

/* Pseudo code of my actual models */ 
class Account(models.Model): 
    fields here... 

class Invoice(models.Model): 
    fields here... 

class InvoiceLineItem(models.Model): 
    account = ForeignKey(Account) 
    invoice = ForeignKey(Invoice) 
    description = CharField 
    amt = DecimalField 

/* === End of Pseudo Code === */ 


# Real code that fails: 

InvoiceLineItemFormset = inlineformset_factory(Invoice, InvoiceLineItem, fields=('description', 'account', 'amt')) 
accts = Account.objects.filter(fund__pk = self.kwargs['fpk']) 
invoice_line_item_form = InvoiceLineItemFormset(form_kwargs={'account':accts}) 

오류는 다음과 같습니다

__init__() got an unexpected keyword argument 'account' 

그리고 오류가 템플릿에서 다음 두 줄 강조한다 :

{{ invoice_line_item_form.management_form }} 
{% for ili in invoice_line_item_form %} 

내가 잘못 구현하고 있는지 잘 모르겠다. (이후로는 formset_factory으로 설계되어있어 inlineformset_factory) 또는 내가 잘못 설정 한 경우. 어떤 아이디어?

답변

2
class InvoiceLineItemForm(forms.ModelForm): 
    def __init__(self, *args, **kwargs): 
     self.account = kwargs.pop('account') 
     super(InvoiceLineItemForm, self).__init__(*args, **kwargs) 
     self.fields['account'].queryset = self.account 

InvoiceLineItemFormSet = inlineformset_factory(
    Invoice, InvoiceLineItem, form=InvoiceLineItemForm, 
    fields=('description', 'account', 'amt')) 

formset = InvoiceLineItemFormSet(form_kwargs={'account': account}) 
+0

솔루션이 매우 근접했습니다. 'ModelForm' :'self.fields [ 'account']. queryset = self.account'에서'super'를 호출 한 직후에 다음을 추가해야했습니다. 답변을 업데이트하면 동의로 표시됩니다. – Garfonzo

+0

@ Garfonzo Edited. 감사! –

관련 문제