从View将值传递给表单-Django

时间:2019-08-25 15:43:07

标签: django django-models django-forms django-views

我有一个视图,其中正在渲染两种形式。两种形式都彼此关联,UpdatePayment(sim_form)和AddPaymentForm(payment_form)。从代码中可以看到,我通过获取sim_form的ID来填充表单。我希望将相同的sim_form ID保存在其中具有sim外键的Payment模型中。但是我无法传递该值,并且表单给出了sim_id为空值的验证错误。

ID即将到来,我也可以使用它。

模型

class Payment(models.Model):
    deposit_date = models.DateField(blank=True, verbose_name='Deposit Date')
    file = models.FileField(upload_to=get_file_path)
    sim = models.ForeignKey(Sim, on_delete=models.DO_NOTHING, null=False, blank=False)

查看

def updatePayment(request, id):
    sim  = get_object_or_404(Sim, pk=id)
    payment_form = AddPaymentForm(request.POST, request.FILES)
    if request.method == "POST":
        sim_form = UpdatePayment(request.POST, instance=sim)
        try:
            if  payment_form.is_valid() and sim_form.is_valid:
                sim_form.save()

                # I am trying to form the value from here
                payment_form.sim_id = id
                payment_form.save()
                messages.success(request, ("Payment has been updated"))
            else:
                messages.warning(request, ("Data in fields is incorrect, please try again"))
        except Exception as e:
            messages.warning(request, ("Error: {}".format(e)))
    else:
        sim_form = UpdatePayment(instance=sim)
        payment_form = AddPaymentForm(request.POST)
    context = {'sim_form': sim_form,'payment_form': payment_form,}
    return render(request, 'payment/updatePayment.html', context)

1 个答案:

答案 0 :(得分:2)

首先,删除sim字段,因为模型形式不需要该字段:

class AddPaymentForm(models.Model):
    class Meta:
       model = Payment
       fields = ('deposit_date', 'file')

然后更新视图以保存sim值,如下所示:

def updatePayment(request, id):
    sim  = get_object_or_404(Sim, pk=id)
    if request.method == "POST":
        payment_form = AddPaymentForm(request.POST, request.FILES)
        sim_form = UpdatePayment(request.POST, instance=sim)
        try:
            if  payment_form.is_valid() and sim_form.is_valid():
                sim_form.save()
                payment = payment_form.save(commit=False)
                payment.sim_id = id
                payment.save()
                messages.success(request, ("Payment has been updated"))
            else:
                messages.warning(request, ("Data in fields is incorrect, please try again"))
        except Exception as e:
            messages.warning(request, ("Error: {}".format(e)))
    else:
        sim_form = UpdatePayment(instance=sim)
        payment_form = AddPaymentForm()
    context = {'sim_form': sim_form,'payment_form': payment_form,}
    return render(request, 'payment/updatePayment.html', context)

在这里,我正在使用payment_form.save(commit=False)生成一个Payment对象,该对象尚未保存到DB。然后我为此对象分配了sim_id并使用.save()方法将其保存到数据库。