2

I have a Decimal Field in my model :

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),
    )

This field is filled with an html form (forms.py was not right for me in this project) and this 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
    )

When submitting the form with an empty value, I got this error :

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

I was expecting my default value to prevent this kind of error. Any idea how can I make this thing right ?

Thanks

Aurélien
  • 1,617
  • 1
  • 21
  • 33

1 Answers1

2

When you post empty value your projectAmount after get is equal to '' try replace:

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

to

dzero = Decimal(0)
postAmount = request.POST.get('projectAmount', dzero)
projectAmount = postAmount if postAmount else dzero
Brown Bear
  • 19,655
  • 10
  • 58
  • 76