Python 在django中提交表单时出现值错误

Python 在django中提交表单时出现值错误,python,django,Python,Django,当我试图通过单击按钮保存表单时,它在产品中的POST方法上给出了一个值错误。这是视图的代码,我想它在product=product.objects.get(id=product\u id)上,我尝试过其他变量,但它不起作用 class LoanApplicationCreateView(AtomicMixin, TemplateView): template_name = 'products/create_loan_application.html' model = LoanApplicatio

当我试图通过单击按钮保存表单时,它在产品中的POST方法上给出了一个值错误。这是视图的代码,我想它在product=product.objects.get(id=product\u id)上,我尝试过其他变量,但它不起作用

class LoanApplicationCreateView(AtomicMixin, TemplateView):
template_name = 'products/create_loan_application.html'
model = LoanApplication
form_class = LoanApplicationCreateForm

def get_object(self, queryset=None):
    """Get loan application request object."""
    return self.model.objects.get(id=self.kwargs.get('id'))

def get_context_data(self, business_id, **kwargs):
    """Get new loan application form view."""
    context = super().get_context_data(**kwargs)
    context = dict()
    context = super(LoanApplicationCreateView, self).get_context_data(**kwargs)
    context['page_name'] = 'new loan application'
    context['title'] = 'Add Loan Application'
    borrower_business = get_object_or_404(Business, pk=business_id)
    context['borrower_business_id'] = borrower_business.id
    context['borrower_business_name'] = borrower_business.business_name
    data = {'borrower_business': borrower_business}
    context['loan_application_form'] = LoanApplicationCreateForm(data=data)
    products = Product.objects.all().values_list('id', 'product_type')
    product_name = Product.objects.all().values_list('product_name')
    context['product_list'] = json.dumps(list(products), cls=DjangoJSONEncoder)

    return context

def post(self, request, business_id):

    loan_application_form = LoanApplicationCreateForm(data=request.POST)

    product_id = request.POST.get('product')
    product = Product.objects.get(id=product_id)
    if loan_application_form.is_valid():
        loan_application_form.save()
    else:
        errors = ''
        for _, error in loan_application_form.errors.items():
            errors = '{} {}'.format(errors, error)
        messages.error(
            request, 'Unable to create the Loan Application. {}'.format(errors), extra_tags='alert alert-danger'
        )
        return HttpResponseRedirect(self.request.META.get('HTTP_REFERER'))
我得到这个错误

ValueError at /products/customer/add_loan_application/414c7d8f-c6e0-4121-940c-8e6dd6a321ec/

Cannot assign "'b724ec73-1e24-440b-a960-2c9972a40839'": "LoanApplication.product" must be a "Product" instance.

您可以在表单的save方法中传递产品实例,就像我在回答中编辑的那样。
product = Product.objects.get(id=product_id) # get the product model object
if loan_application_form.is_valid():
    loan_application_form.save(commit=False)
    loan_application_form.product = product # assign the product instance to product column
    loan_application_form.save() # save the form`enter code here`


or the other way is to save the instance in your form by passing the instance to your form save method

views.py

product = Product.objects.get(id=product_id) # get the product model object
if loan_application_form.is_valid():
    loan_application_form.save(product)


forms.py

In your LoanApplicationCreateForm class, need to write the save method

        def save(self, product, commit=True):
            instance = super(LoanApplicationCreateForm, self).save(commit=False)

            if not self.instance.pk:
                # create
                if commit:
                    instance.product = product
                    instance.save()
            return instance