2017-08-27 48 views
0

我有一個小數場在我的模型:django.core.exceptions.validationerror'值必須是一個十進制數

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

當您張貼空值的projectAmount獲取之後,等於'' 嘗試更換:

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

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

感謝熊布朗 –