简体   繁体   中英

Python Validate to only allow Numbers and 2 Decimals

was wondering if anyone could help me to validate my entries to only allow numeric values with two decimal places.

Here is the models.py:

class Records(models.Model):
    capital = models.DecimalField(max_digits=10, decimal_places=2)
    years = models.DecimalField(max_digits=10, decimal_places=2)
    rate = models.DecimalField(max_digits=10, decimal_places=2)
    amount = models.DecimalField(max_digits=10, decimal_places=2)

You could do this on the Model or in a Form.

Django has a built-in validator for just this case:

from django.core.validators import DecimalValidator
...
# In the model:
capital = models.DecimalField(max_digits=10, decimal_places=2, validators=[DecimalValidator])

# Or in a Form:
capital = forms.DecimalField(max_digits=10, decimal_places=2, validators=[DecimalValidator])

I think you have defined the models quite well. To validate the model, you can use the clean_fields() or clean() methods of the Django Model class. You can read more about django model validation here

You could write and add custom validator to your fields

Django validators

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM