在"Passing custom parameters to formset forms"上关注Django文档时,我得到以下内容:
__init__() got an unexpected keyword argument 'choices'
File "/Users/emilepetrone/Envs/kishikoi/lib/python3.6/site-packages/django/utils/functional.py" in __get__
35. res = instance.__dict__[self.name] = self.func(instance)
File "/Users/emilepetrone/Envs/kishikoi/lib/python3.6/site-packages/django/forms/formsets.py" in forms
144. for i in range(self.total_form_count())]
File "/Users/emilepetrone/Envs/kishikoi/lib/python3.6/site-packages/django/forms/formsets.py" in <listcomp>
144. for i in range(self.total_form_count())]
File "/Users/emilepetrone/Envs/kishikoi/lib/python3.6/site-packages/django/forms/formsets.py" in _construct_form
182. form = self.form(**defaults)
File "/Users/emilepetrone/Sites/kishikoi/kishikoi/transactions/forms.py" in __init__
119. super(SoldTransactionForm, self).__init__(*args, **kwargs)
Exception Type: TypeError at /transactions/create/sell/transactions/31tmhqsplg41jc8c/
Exception Value: __init__() got an unexpected keyword argument 'choices'
以下是我查看文档并通过“选择”的视图。在formset form_kwargs。
class SellTransactionsView(LoginRequiredMixin, SetHeadlineMixin, UpdateView):
model = Transaction
template_name = "transactions/soldtransaction_form.html"
headline = "Sell Transaction"
fields = ['num_shares']
def get_object(self):
return Transaction.objects.get(
user=self.request.user,
identifier=self.kwargs['identifier']
)
def get_choices(self):
transaction = self.get_object()
choices = Transaction.objects.filter(
user=transaction.user,
).exclude(identifier=transaction.identifier)
return choices
def get_context_data(self, *args, **kwargs):
context = super(SellTransactionsView, self).get_context_data(
*args, **kwargs)
choices = self.get_choices()
formset = SoldFormset(form_kwargs={'choices': choices})
context.update({
"formset": formset,
})
return context
我的表格&amp; Formset - 我使用forms.Form因为我将使用这些字段来更新form.is_valid()中的不同字段。
class SoldTransactionForm(forms.Form):
old_transaction = forms.ChoiceField()
num_shares = forms.IntegerField(
min_value=0
)
class Meta:
fields = [
'old_transaction',
'num_shares',
]
def __init__(self, *args, **kwargs):
super(SoldTransactionForm, self).__init__(*args, **kwargs)
self.fields['old_transaction'].queryset = kwargs.pop('choices')
SoldFormset = forms.formset_factory(
SoldTransactionForm,
formset=forms.BaseFormSet,
extra=2
)
解
对于其他人来说,kwargs.pop(&#39;选择&#39;)确实需要高于表单中的Super()。 init
这解决了错误,但随后呈现了一个formset而没有在ChoiceField中加载数据。我将字段更改为ModelChoiceField&amp; set queryset = None(在 init 中进行更改。这解决了问题。
答案 0 :(得分:3)
在致电super
之前弹出:
def __init__(self, *args, **kwargs):
queryset = kwargs.pop('choices')
super(SoldTransactionForm, self).__init__(*args, **kwargs)
self.fields['old_transaction'].queryset = queryset