David S
David S

Reputation: 13841

Django Models - Prepare the data for the database

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.

Upvotes: 1

Views: 1750

Answers (3)

Your question specifically about point 3 is a little different from "cleaning" in the way django uses the term.

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.

Point 3 is about converting the python object values to one suitable for a database. Specifically, this is done in Field.get_prep_value and Field.get_db_prep_value

https://docs.djangoproject.com/en/dev/howto/custom-model-fields/#django.db.models.Field.get_prep_value

It's the opposite of to_python which 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 Fields clean method (subclass IntegerField), form clean method, form clean_FIELDNAME method, or model clean.

Upvotes: 2

tamakisquare
tamakisquare

Reputation: 17067

use django model form + custom form field cleaning

Below is a quick example of what you might be looking for, where MyModel is the model containing the phone number field, which I named it tel here.

import re

class MyForm(ModelForm):
    class Meta:
        model = MyModel

    def clean_tel(self):
        tel = self.cleaned_data.get('tel', '')  # this is from user input

        # use regular expression to check if tel contains only digits; you might wanna enhance the regular expression to restrict the tel number to have certain number of digits.
        result = re.match(r'\d+', tel)  
        if result:
            return tel  # tel is clean so return it
        else:
            raise ValidationError("Phone number contains invalid character.") 

Upvotes: 0

Hacking Life
Hacking Life

Reputation: 3373

You can add a custom Form Cleaning method to your objects model - take a look at this article https://docs.djangoproject.com/en/dev/ref/forms/validation/#form-field-default-cleaning

Look at "Cleaning a specific field attribute"

Upvotes: 1

Related Questions