【问题标题】:django.core.exceptions.validationerror '' value must be a decimal number [duplicate]django.core.exceptions.validationerror '' 值必须是十进制数 [重复]
【发布时间】:2018-02-04 19:30:40
【问题描述】:

我的模型中有一个小数字段:

models.py

from django.db import models
from django.utils import timezone
from datetime import datetime

from decimal import Decimal

class Simulation(models.Model):
    projectAmount = models.DecimalField(max_digits=19,
                                        decimal_places=2,
                                        verbose_name='Amount',
                                        blank=True,
                                        default=Decimal(0),
    )

这个字段填充了一个 html 表单(forms.py 在这个项目中不适合我)和这个 views.py

views.py

from django.shortcuts import get_object_or_404, render

from decimal import Decimal

from .models import Simulation

def simulation_create(request):
    if request.method == 'POST':
        projectAmount = request.POST.get('projectAmount', '0.00')

    Simulation.objects.create(
                projectAmount = projectAmount
    )

当提交一个空值的表单时,我收到了这个错误:

django.core.exceptions.ValidationError: ['Value must be a decimal 
number']

我希望我的默认值能够防止这种错误。 知道如何才能使这件事正确吗?

谢谢

【问题讨论】:

    标签: python django django-models django-views


    【解决方案1】:

    当您发布空值时,您的projectAmount 在获取后等于'' 尝试替换:

    projectAmount = request.POST.get('projectAmount', '0.00')
    

    dzero = Decimal(0)
    postAmount = request.POST.get('projectAmount', dzero)
    projectAmount = postAmount if postAmount else dzero
    

    【讨论】:

    • 感谢熊布朗
    猜你喜欢
    • 1970-01-01
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    • 2013-03-28
    • 2019-01-05
    • 2021-02-05
    • 1970-01-01
    相关资源
    最近更新 更多