其他分享
首页 > 其他分享> > __init __()获得了意外的关键字参数’instance’,具有针对inlineformset_factory的自定义格式集

__init __()获得了意外的关键字参数’instance’,具有针对inlineformset_factory的自定义格式集

作者:互联网

我收到这个错误

__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,则您的formset类应继承BaseInlineFormSet.

from django.forms import BaseInlineFormSet

class PurchaseFormSet(BaseInlineFormSet):
    ...

标签:python-3-x,django-forms,python,django
来源: https://codeday.me/bug/20191111/2017662.html