gpt4 book ai didi

python - __init__() 得到了一个意外的关键字参数 'instance',带有 inlineformset_factory 的自定义表单集

转载 作者:太空宇宙 更新时间:2023-11-03 15:53:10 27 4
gpt4 key购买 nike

我遇到了这个错误

__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)

最佳答案

如果您正在使用 inlineformset_factory,那么您的表单集类应该继承 BaseInlineFormSet

from django.forms import BaseInlineFormSet

class PurchaseFormSet(BaseInlineFormSet):
...

关于python - __init__() 得到了一个意外的关键字参数 'instance',带有 inlineformset_factory 的自定义表单集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45297908/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com