我的模型中有一个十进制字段:
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']
我希望我的默认值可以防止出现这种错误。 任何想法我怎样才能做到这一点?
由于
答案 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