[Django] Create a model suitable for phone numbers / zip codes

When creating an application with Django alone, it may be better to validate with form, but if you mainly provide API as Django REST Framework, you also want to validate with Model Below is an example of validating phone number and zip code fields

models.py


from django.db import models
from django.core.validators import RegexValidator

class SampleModel(model.model):
	tel_number_regex = RegexValidator(regex=r'^[0-9]+$', message = ("Tel Number must be entered in the format: '09012345678'. Up to 15 digits allowed."))
	tel_number = models.CharField(validators=[tel_number_regex], max_length=15, verbose_name='phone number')
	postal_code_regex = RegexValidator(regex=r'^[0-9]+$', message = ("Postal Code must be entered in the format: '1234567'. Up to 7 digits allowed."))
	postal_code = models.CharField(validators=[postal_code_regex], max_length=7, verbose_name='Postal code') 

This way you can validate with regular expressions If you send a request that does not match, the message set for each will be returned.

If you want to save the record with a hyphen, it is better to write a regular expression suitable for it in regex =

As an aside, I wish I could set max_length when I defined each regular expression, but I couldn't.

Recommended Posts

[Django] Create a model suitable for phone numbers / zip codes
Create a model for your Django schedule
Create a dashboard for Network devices with Django!
Create a Django schedule
Create a homepage with django
Create a Django login screen
Create a social integration API for smartphone apps with Django
[Python] Create a screen for HTTP status code 403/404/500 with Django
Steps to create a Django project
Create a file uploader with Django
Create a LINE Bot in Django
Create a survival prediction model for Kaggle Titanic passengers without using Python
Let's create a virtual environment for Python
Commands for creating a new django project
Build a TOP screen for Django users
Get a reference model using Django Serializer
Create a Hatena dictionary for SKK (additional)
Implement a Custom User Model in Django
Write a short if-else for Django Template
[Django] Create a form that automatically fills in the address from the zip code