我收到此错误
__init__() got an unexpected keyword argument 'instance'
每当我尝试发送一个带有为inlineformset_factory指定的formset参数的表单时。 任何想法为什么会发生这种情况?
这是我的代码。对不起它没有评论我正在重写它,试图理解django如何工作
class PurchaseForm(forms.ModelForm):
class Meta:
model = Purchase
fields = ['product', 'price', 'consumer']
widgets = {
'product': forms.Select(attrs = {
'class': 'form-control input-sm',
}),
'consumer': forms.Select(attrs = {
'class': 'form-control input-sm',
}),
'price': forms.NumberInput(attrs = {
'class': 'form-control input-sm',
'placeholder': 'Цена',
}),
}
discount = forms.DecimalField(
min_value = 0,
decimal_places = 2,
# required = False,
widget = forms.NumberInput(
attrs = {
'class': 'form-control input-sm',
'placeholder': 'Скидка'
}
),
)
class PurchaseFormSet(BaseModelFormSet):
def add_fields(self, form, index):
super(PurchaseFormSet, self).add_fields(form, index)
form.fields[DELETION_FIELD_NAME].label = ''
def receipt(request):
purchase_formset = inlineformset_factory(
Receipt,
Purchase,
form = PurchaseForm,
formset = PurchaseFormSet, <-- when I comment this everything works fine
)
if request.method == 'POST':
receipt_form = ReceiptForm(
request.POST,
prefix = 'receipt'
)
if receipt_form.is_valid():
receipt = receipt_form.save()
receipt_form = ReceiptForm(
instance = receipt,
prefix = 'receipt'
)
purchases_form = purchase_formset(
request.POST,
prefix = 'purchase',
instance = receipt <-- line that causes error according to traceback
)
if purchases_form.is_valid():
purchases_form.save()
return redirect('spendings:receipt')
else:
receipt_form = ReceiptForm(
instance = Receipt(),
prefix = 'receipt'
)
purchases_form = purchase_formset(
prefix = 'purchase'
)
context = {
'receipt_form': receipt_form,
'purchases_form': purchases_form
}
return render(request, 'spendings/receipt/index.html', context)
答案 0 :(得分:3)
如果您使用的是inlineformset_factory
,那么您的formset类应该继承BaseInlineFormSet
。
from django.forms import BaseInlineFormSet
class PurchaseFormSet(BaseInlineFormSet):
...