Daniiii
Daniiii

Reputation: 15

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)

Upvotes: 1

Views: 2616

Answers (3)

brian buck
brian buck

Reputation: 3454

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

Upvotes: 1

iklinac
iklinac

Reputation: 15738

You could write and add custom validator to your fields

Django validators

Upvotes: 0

hassan
hassan

Reputation: 185

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

Upvotes: 0

Related Questions