django.core.exceptions.validationerror''值必须是十进制数

时间:2017-08-27 09:35:04

标签: python django django-models django-views

我的模型中有一个十进制字段:

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']

我希望我的默认值可以防止出现这种错误。 任何想法我怎样才能做到这一点?

由于

1 个答案:

答案 0 :(得分:1)

当你发布空值后,你的projectAmount等于'' 尝试替换:

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

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