Django Model EmailField Explanation
Illustration of EmailField using an Example. Consider a project named w3wiki having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
Enter the following code into models.py file of geeks app.
Python3
from django.db import models from django.db.models import Model # Create your models here. class GeeksModel(Model): geeks_field = models.EmailField(max_length = 254 ) |
Add the geeks app to INSTALLED_APPS
Python3
# Application definition INSTALLED_APPS = [ 'django.contrib.admin' , 'django.contrib.auth' , 'django.contrib.contenttypes' , 'django.contrib.sessions' , 'django.contrib.messages' , 'django.contrib.staticfiles' , 'geeks' , ] |
Now when we run makemigrations command from the terminal,
Python manage.py makemigrations
A new folder named migrations would be created in geeks directory with a file named 0001_initial.py
Python3
# Generated by Django 2.2.5 on 2019-09-25 06:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name = 'GeeksModel' , fields = [ ( 'id' , models.AutoField( auto_created = True , primary_key = True , serialize = False , verbose_name = 'ID' )), ( 'geeks_field' , models.EmailField( max_length = 254 )), ], ), ] |
Now run,
Python manage.py migrate
Thus, an geeks_field EmailField is created when you run migrations on the project. It is a field to store email address in database.
EmailField – Django Models
EmailField is a CharField that checks the value for a valid email address using EmailValidator. EmailValidator validates a email through predefined regex which checks ‘@’ and a ‘.’ defined after it. One can change the regex by exploring options from EmailValidator itself. Syntax
field_name = models.EmailField(max_length=254, **options)
EmailField has one extra required argument:
EmailField.max_length
The maximum length (in characters) of the field. The max_length is enforced at the database level and in Django’s validation using MaxLengthValidator.
Contact Us