Post数据具有表单输入,但Django modelform未保存它

问题描述 投票:0回答:1

我浏览了许多其他文章-但找不到适合我的情况的任何内容。我在POST中遇到了一些数据,但是当我保存表单时-数据没有出现在数据库中。

我对为什么会这样有些困惑,我尝试了各种方法,但是似乎没有一种方法真正适用于我的情况。大多数情况与未发布数据有关,我的数据已发布,只是没有保存。

我有以下模型:

class Payment(models.Model):
    METHODS = (
        ("Cash", "Cash"),
        ("Check", "Check"),
        ("Credit Card", "Credit Card")
    )
    amount = models.DecimalField(decimal_places=2, max_digits=6)
    method = models.CharField(
        max_length=15,
        choices=METHODS,
        default="Credit Card"
    )
    stripe_id = models.CharField(max_length=255, blank=True, null=True)
    check_number = models.IntegerField(blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)

这是我的PaymentForm:

class PaymentForm(forms.ModelForm):
    method = forms.CharField(
        max_length=25,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            "readonly": "True",
            })
        )
    amount = forms.DecimalField(
        decimal_places=2,
        max_digits=6,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            "readonly": "True",
            })
        )
    stripe_id = forms.CharField(
        widget=forms.HiddenInput(),
        required=False
    )
    check_number = forms.IntegerField(
        widget=forms.TextInput(attrs={"class": "form-control"}),
        required=False
    )

    class Meta:
        model = Payment
        fields = (
            'amount',
            'method',
            'stripe_id',
            'check_number',
        )

    def clean_check_number(self):
        method = self.cleaned_data["method"]
        check_number = self.cleaned_data["check_number"]
        if method == "Check" and not check_number:
            raise forms.ValidationError("Check number is required.")

这里是我的与开机自检相关的view.py函数:

    if request.method == "POST":
        # Create a copy of the POST data so we can input data for CC payments
        post_data = request.POST.copy()
        # Set the PaymentForm with the copied data (muteable)
        # required for some of the stripe stuff we do
        payment_form = PaymentForm(post_data)

        if 'stripeToken' in request.POST:
            # This is wrapped in extensive try/catch in reality but I left
            # it out for brevity
            charge = stripe.Charge.create(
                amount=stripe_cost,
                currency="usd",
                description="Payment",
                source=request.POST["stripeToken"],
                receipt_email=request.POST["stripeEmail"],
            )
            # add things to the form that aren't there
            # from the stripe reply
            payment_form.data['method'] = "Credit Card"
            payment_form.data['stripe_id'] = charge["id"]
            # This part works fine
        if payment_form.is_valid():
            # either a non-stripe payment
            # or the next step after the stripe stuff is don
            payment_form.save(commit=False)
            print(payment_form.data)
            payment = payment_form.save()
            # The data saves to the DB, but the check_number is empty!
        messages.success(request, "Thank you for your payment!")
        return redirect("my_app:index") 

表格有效后的打印声明将像这样打印出来:

<QueryDict: {'csrfmiddlewaretoken': ['3blahblahblah'], 'amount': ['9.10'], 'method': ['Check'], 'check_number': ['123455'], 'stripe_id': ['']}>

我遇到的问题是:当用户选择Check作为付款并保存付款(带有支票号码)时,支票号码没有保存到数据库中。

如我们所见,request.POST数据显示了那里的所有数据(包括支票号码)-但是当check_number运行时,.save()没有存储在数据库中。

可能导致这种情况发生,以及如何对此进行修正?

python django django-forms modelform
1个回答
0
投票

is_valid之后,您应该打印form.cleaned_data,而不是form.data。如果这样做,您会看到check_number为空。这样做的原因是,您没有从clean_check_number方法中返回任何内容。您始终需要从这些方法中返回清理后的值。

© www.soinside.com 2019 - 2024. All rights reserved.