'ValidationError at /opd/ ['“OPDCashSheet object (2)” value must be a decimal number.'] How can a model-object be a decimal number?

models.py:

class Opd(models.Model):
    patient=models.ForeignKey(Patient, on_delete=CASCADE)
    bill_number=models.IntegerField(default=None)
    date=models.DateField(default=datetime.date.today)
    service_name=models.ForeignKey(ServiceName, on_delete=SET_NULL, null=True)
    mode=models.CharField(max_length=5, default=None)
    amount=models.DecimalField(max_digits=7, decimal_places=2)
    remarks=models.TextField(max_length=500, blank=True, default=None)
    opd_date=models.DateTimeField(auto_now_add=True)
    modified_on=models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.patient.name

class OPDParticulars(models.Model):
    opd_particulars=models.CharField(max_length=150)

    def __str__(self):
        return self.opd_particulars

class OPDCashSheet(models.Model):
    date=models.DateField(default=datetime.date.today)
    patient=models.ForeignKey(Patient, on_delete=SET_NULL, blank=True, null=True)
    opd=models.ForeignKey(Opd, on_delete=SET_NULL, null=True, blank=True)
    opd_particulars=models.ForeignKey(OPDParticulars, on_delete=SET_NULL, null=True, blank=True)
    source=models.CharField(max_length=10, default='OPD', null=True, blank=True)
    case_number=models.IntegerField(null=True, blank=True)
    mode=models.CharField(max_length=5)
    cash_in=models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True)
    cash_out=models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True)
    balance=models.DecimalField(max_digits=7, decimal_places=2, default=0)
    bank_oopl=models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True)
    remarks=models.TextField(max_length=500, blank=True, null=True, default=None)
    created_on=models.DateTimeField(auto_now_add=True)
    modified_on=models.DateTimeField(auto_now=True)

class BankDeposits(models.Model):
    opdcashsheet=models.ForeignKey(OPDCashSheet, on_delete=SET_NULL, null=True, blank=True)
    date=models.DateField(default=None)
    amount=models.DecimalField(max_digits=7, decimal_places=2, default=None)
    bank=models.CharField(max_length=70, default=None, null=True, blank=True)
    mode=models.CharField(max_length=5, default=None)
    bank_ac=models.CharField(max_length=25, default='ABC Pvt. 123456789')
    branch=models.CharField(max_length=20, default='XYZ')
    remarks=models.TextField(max_length=500, blank=True, null=True, default=None)
    created_on=models.DateTimeField(auto_now_add=True)
    modified_on=models.DateTimeField(auto_now=True)

forms.py:

class UpdateOPDCashSheetForm(ModelForm):
    MODE_SELECT = (
        ('cash', 'Cash'),
        ('bank', 'Bank'),
    )
    mode=forms.CharField(widget=forms.RadioSelect(choices=MODE_SELECT, attrs={'class': 'form-check-inline'}))
    class Meta:
        model=OPDCashSheet
        labels={
            'cash_in':'Cash-in',
            'cash_out':'Cash-Out',
            'balance':'Cash Balance',
            'bank_oopl':'To Bank',
            'opd_particulars':'Description',
        }
        fields='__all__'
        widgets={
            'date': DateInput(attrs={'type': 'date'}),
        }

class BankDepositsForm(ModelForm):
    MODE_SELECT = (
        ('cash', 'Cash'),
        ('bank', 'Bank'),
    )
    mode=forms.CharField(widget=forms.RadioSelect(choices=MODE_SELECT, attrs={'class': 'form-check-inline'}))
    class Meta:
        model=BankDeposits
        labels={
            'bank_ac':'Bank A/c',
        }
        fields='__all__'
        widgets={
            'date': DateInput(attrs={'type': 'date'}),
        }

class OpdForm(ModelForm):
    MODE_SELECT = (
        ('cash', 'Cash'),
        ('bank', 'Bank'),
    )
    mode=forms.CharField(widget=forms.RadioSelect(choices=MODE_SELECT, attrs={'class': 'form-check-inline'}))
    class Meta:
        model=Opd
        fields='__all__'
        widgets={
            'date': DateInput(attrs={'type': 'date'}),
        }

views.py:

def opd_view(request):
    if request.method=='POST':
        fm_opd=OpdForm(request.POST)
        if fm_opd.is_valid():
            opd=fm_opd.save()
            OpdReport.objects.create(patient=opd.patient, opd=opd)
            if opd.mode=='cash':
                OPDCashSheet.objects.create(date=opd.date, patient=opd.patient, opd=opd, case_number=opd.bill_number, mode=opd.mode, cash_in=opd.amount)
            elif opd.mode=='bank':
                opdcashsheet=OPDCashSheet.objects.create(date=opd.date, patient=opd.patient, opd=opd, case_number=opd.bill_number, mode=opd.mode, bank_oopl=opd.amount)
                BankDeposits.objects.create(opdcashsheet=opdcashsheet.id, date=opd.date, amount=opd.amount, mode=opd.mode, remarks=opd.remarks)
            fm_opd=OpdForm()
        return render(request, 'account/opd.html', {'form1':fm_opd})
    else:
        fm_opd=OpdForm()
        return render(request, 'account/opd.html', {'form1':fm_opd})

Coming to the view, it worked fine when the mode was cash and it created the object for OPDCashSheet but when the mode is bank, it can not create an object for the same model, stating a ValidationError - ['“OPDCashSheet object (2)” value must be a decimal number.']. Now if this object could be created, it would have been the OPDCashSheet object (3) as the second object is already saved in the database. So where am I going wrong here? How can a model object be a decimal field? Please help.

EDIT: Error Traceback:

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/opd/

Django Version: 4.0
Python Version: 3.10.1
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'account',
 'mathfilters',
 'django_filters']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\__init__.py", line 1551, in to_python
    return decimal.Decimal(value)

During handling of the above exception (conversion from OPDCashSheet to Decimal is not supported), another exception occurred:
  File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "H:\Sonu\Projects\Practice\Project versions\Roughs\slr\2. wrkg\rough1\account\views.py", line 15422, in opd_view
    opdcashsheet=OPDCashSheet.objects.create(date=opd.date, patient=opd.patient, opd=opd, case_number=opd.bill_number, mode=opd.mode, bank_oopl=opd.amount)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 457, in create
    obj.save(force_insert=True, using=self.db)
  File "H:\Sonu\Projects\Practice\Project versions\Roughs\slr\2. wrkg\rough1\account\models.py", line 139, in save
    super(OPDCashSheet, self).save(*args, **kwargs)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\base.py", line 743, in save
    self.save_base(using=using, force_insert=force_insert,
  File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\base.py", line 780, in save_base
    updated = self._save_table(
  File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\base.py", line 885, in _save_table
    results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\base.py", line 923, in _do_insert
    return manager._insert(
  File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 1301, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\sql\compiler.py", line 1440, in execute_sql
    for sql, params in self.as_sql():
  File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\sql\compiler.py", line 1382, in as_sql
    value_rows = [
  File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\sql\compiler.py", line 1383, in <listcomp>
    [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
  File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\sql\compiler.py", line 1383, in <listcomp>
    [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
  File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\sql\compiler.py", line 1324, in prepare_value
    value = field.get_db_prep_save(value, connection=self.connection)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\__init__.py", line 1560, in get_db_prep_save
    return connection.ops.adapt_decimalfield_value(self.to_python(value), self.max_digits, self.decimal_places)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\__init__.py", line 1553, in to_python
    raise exceptions.ValidationError(

Exception Type: ValidationError at /opd/
Exception Value: ['“OPDCashSheet object (2)” value must be a decimal number.']


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source