首页 > 解决方案 > Django Formset 新条目验证失败

问题描述

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

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

视图.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)

标签: djangodjango-viewsdjango-forms

解决方案


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


推荐阅读