I have a form that askes for a phone number. I need to make sure that only digits [0-9] get saved in the database.
In the Django documentation it says:
What happens when you save?
3) Prepare the data for the database. Each field is asked to provide its current value in a data type that can be written to the database.
How does this happen? Or more specifically, how can I make sure this is cleaned? I know that I can just override the models save method, but it seems like there is a better way and I’m just not sure how to do it.
I guess I could write a custom field for it, but that seems like overkill here.
Also, I realize that I can put the validation on the form, but it really feels like stripping out the characters belongs on the model.
Your question specifically about point 3 is a little different from “cleaning” in the way django uses the term.
Point 3 is about converting the python object values to one suitable for a database. Specifically, this is done in
Field.get_prep_valueandField.get_db_prep_valuehttps://docs.djangoproject.com/en/dev/howto/custom-model-fields/#django.db.models.Field.get_prep_value
It’s the opposite of
to_pythonwhich takes a DB value and converts it to a python object.As for ensuring only digits 0-9 get stored, that would be done in a
Fieldscleanmethod (subclass IntegerField), formcleanmethod, formclean_FIELDNAMEmethod, or modelclean.