Django Formset 新条目验证失败

Django Formset new entry fails validation

我正在尝试创建一个表单集,我可以在其中 1) 显示所有条目 +1(对于新条目)2) 更新现有条目 3) 添加新条目。目前我可以成功完成 1 和 2。当涉及到添加新条目时,表单集失败 .is_valid() 检查。这是因为我有一个 entry_id 的隐藏输入。该 id 是 bulk_update() 更新现有条目所必需的,但会导致 is_valid() 函数在新条目上失败。如果我使用 bulk_create(),我不需要 ID,但它会复制所有现有条目。

有没有办法在尝试添加新条目时通过 .is_valid() 检查?

views.py

def CustomerView(request):
    template = "accounts/customers.html"
    # Create the formset, specifying the form and formset we want to use.
    CustomerFormSet = formset_factory(CustomerForm, formset=BaseFormSet)

    # Get our existing data for this user.
    customer_list = Customers.objects.all().order_by("cust_name")
    customers = [{'customer_id': c.id, 'customer_name': c.cust_name}
                    for c in customer_list]

    if request.method == 'POST':
        customer_formset = CustomerFormSet(request.POST)
        # print(customer_formset.errors)
        if customer_formset.is_valid():
            # Now save the data for each form in the formset
            customer = []
            
            for customer_form in customer_formset:
                customer_id = customer_form.cleaned_data.get('customer_id')
                customer_name = customer_form.cleaned_data.get('customer_name')
                
                if customer_id and customer_name:
                        customer.append(Customers(id=customer_id, cust_name=customer_name))
            try:
                with transaction.atomic():
                    #Replace the old with the new
                    Customers.objects.filter(id=customer_id).delete()
                    Customers.objects.bulk_create(customer)
                    
                    # And notify our users that it worked
                    messages.success(request, 'Saved Successfully.')

            except IntegrityError: #If the transaction failed
                messages.error(request, 'There was an error saving.')
                return redirect('/customers')
        else: #If the form is not valid
            messages.error(request, 'The form is not valid.')
            
            return redirect('/customers')

    else:
        customer_formset = CustomerFormSet(initial=customers)

    data = {
        'customer_formset': customer_formset,
    }

    return render(request, template, data)

让entry_id在表单中不需要,然后你可以在验证后在视图上检查它来决定更新或添加元素