DecimalField验证错误,返回不正确的值Django

bq3bfh9z  于 2022-11-19  发布在  Go
关注(0)|答案(1)|浏览(120)

我在我的一个表单中有一个DecimalField,用户可以在其中输入价格。
假设用户输入11.00,现在当我按照(priceform.cleaned_data)检索它时,它将返回

Decimal('11.00')

所以看起来

price = Decimal('11.00')

当我试图将其插入数据库时,它会触发验证错误。
我对这件事一片空白

模型.py

class Bid(models.Model):
    title = models.CharField(max_length=64, blank=True)
    date_time = models.DateTimeField(default=timezone.now, blank=True)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    user = models.CharField(max_length=64)

表单.py:

class BidForm(ModelForm):
    class Meta:
        model = Bid
        fields = ['price']

查看次数.py:

if request.method == "POST":
      bidform = BidForm(request.POST)
      if bidform.is_valid():
            price = bidform.cleaned_data['price']
            bid = Bid.objects.create(title=title, price=bidform, user=username)
            bid.save()
7uhlpewt

7uhlpewt1#

price应该是price,而不是bidform

if request.method == 'POST':
    bidform = BidForm(request.POST, request.FILES)
    if bidform.is_valid():
        bid = Bid.objects.create(
            title=title,
            price=bidform.cleaned_data['price'],
            user=username
        )

不过,您可以让表单执行这项工作:

if request.method == 'POST':
    bid = Bid(
        title=title,
        user=username
    )
    bidform = BidForm(request.POST, request.FILES, instance=bid)
    if bidform.is_valid():
        bid = bidform.save()

相关问题