├── accounts ├── __init__.py ├── migrations │ ├── __init__.py │ └── 0001_initial.py ├── tests.py ├── apps.py ├── templates │ ├── register.html │ └── registration │ │ └── login.html ├── forms.py ├── views.py ├── admin.py └── models.py ├── cb_dj_custom_user_model ├── __init__.py ├── asgi.py ├── wsgi.py ├── urls.py └── settings.py ├── templates └── admin │ └── auth │ └── user │ └── add_form.html ├── manage.py ├── .gitignore └── README.md /accounts/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /accounts/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /cb_dj_custom_user_model/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /accounts/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /accounts/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class AccountsConfig(AppConfig): 5 | name = 'accounts' 6 | -------------------------------------------------------------------------------- /accounts/templates/register.html: -------------------------------------------------------------------------------- 1 |
2 | {% csrf_token %} 3 | {{ form.as_p }} 4 | 5 |
-------------------------------------------------------------------------------- /accounts/templates/registration/login.html: -------------------------------------------------------------------------------- 1 |
2 | {% csrf_token %} 3 | {{ form.as_p }} 4 | 5 |
-------------------------------------------------------------------------------- /accounts/forms.py: -------------------------------------------------------------------------------- 1 | from django.contrib.auth import get_user_model 2 | from django.contrib.auth.forms import UserCreationForm 3 | 4 | 5 | class UserAdminCreationForm(UserCreationForm): 6 | """ 7 | A Custom form for creating new users. 8 | """ 9 | 10 | class Meta: 11 | model = get_user_model() 12 | fields = ['email'] -------------------------------------------------------------------------------- /templates/admin/auth/user/add_form.html: -------------------------------------------------------------------------------- 1 | {% extends "admin/change_form.html" %} 2 | {% load i18n %} 3 | 4 | {% block form_top %} 5 | {% if not is_popup %} 6 |

First, enter an email and password. Then, you’ll be able to edit more user options.

7 | {% else %} 8 |

Enter an email and password./p> 9 | {% endif %} 10 | {% endblock %} -------------------------------------------------------------------------------- /cb_dj_custom_user_model/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for cb_dj_custom_user_model project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cb_dj_custom_user_model.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /cb_dj_custom_user_model/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for cb_dj_custom_user_model project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cb_dj_custom_user_model.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /accounts/views.py: -------------------------------------------------------------------------------- 1 | from django.contrib.auth.decorators import login_required 2 | from django.contrib.auth.forms import UserCreationForm 3 | from django.shortcuts import render, redirect 4 | # from accounts.forms import UserAdminCreationForm 5 | from accounts.forms import UserAdminCreationForm 6 | 7 | @login_required() 8 | def register(req): 9 | form = UserAdminCreationForm() 10 | if req.method == 'POST': 11 | form = UserAdminCreationForm(req.POST) 12 | if form.is_valid(): 13 | form.save() 14 | return redirect('register') 15 | return render(req, 'register.html', {'form': form}) -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cb_dj_custom_user_model.settings') 9 | try: 10 | from django.core.management import execute_from_command_line 11 | except ImportError as exc: 12 | raise ImportError( 13 | "Couldn't import Django. Are you sure it's installed and " 14 | "available on your PYTHONPATH environment variable? Did you " 15 | "forget to activate a virtual environment?" 16 | ) from exc 17 | execute_from_command_line(sys.argv) 18 | 19 | 20 | if __name__ == '__main__': 21 | main() 22 | -------------------------------------------------------------------------------- /cb_dj_custom_user_model/urls.py: -------------------------------------------------------------------------------- 1 | """cb_dj_custom_user_model URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/3.0/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path, include 18 | 19 | from accounts import views 20 | 21 | urlpatterns = [ 22 | path('admin/', admin.site.urls), 23 | path('register/', views.register, name='register'), 24 | path('accounts/', include('django.contrib.auth.urls')), 25 | ] 26 | -------------------------------------------------------------------------------- /accounts/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from django.contrib.auth.admin import UserAdmin 3 | from django.utils.translation import ugettext_lazy as _ 4 | from django.contrib.auth import get_user_model 5 | 6 | 7 | class CustomUserAdmin(UserAdmin): 8 | """Define admin model for custom User model with no username field.""" 9 | fieldsets = ( 10 | (None, {'fields': ('email', 'password')}), 11 | (_('Personal info'), {'fields': ('first_name', 'last_name')}), 12 | (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 13 | 'groups', 'user_permissions')}), 14 | (_('Important dates'), {'fields': ('last_login', 'date_joined')}), 15 | ) 16 | add_fieldsets = ( 17 | (None, { 18 | 'classes': ('wide',), 19 | 'fields': ('email', 'password1', 'password2'), 20 | }), 21 | ) 22 | list_display = ('email', 'first_name', 'last_name', 'is_staff') 23 | search_fields = ('email', 'first_name', 'last_name') 24 | ordering = ('email',) 25 | 26 | 27 | admin.site.register(get_user_model(), CustomUserAdmin) -------------------------------------------------------------------------------- /accounts/models.py: -------------------------------------------------------------------------------- 1 | from django.contrib.auth.models import AbstractUser, BaseUserManager 2 | from django.db import models 3 | from django.utils.translation import ugettext_lazy as _ 4 | 5 | 6 | class CustomUserManager(BaseUserManager): 7 | """Define a model manager for User model with no username field.""" 8 | 9 | def _create_user(self, email, password=None, **extra_fields): 10 | """Create and save a User with the given email and password.""" 11 | if not email: 12 | raise ValueError('The given email must be set') 13 | email = self.normalize_email(email) 14 | user = self.model(email=email, **extra_fields) 15 | user.set_password(password) 16 | user.save(using=self._db) 17 | return user 18 | 19 | def create_user(self, email, password=None, **extra_fields): 20 | extra_fields.setdefault('is_staff', False) 21 | extra_fields.setdefault('is_superuser', False) 22 | return self._create_user(email, password, **extra_fields) 23 | 24 | def create_superuser(self, email, password=None, **extra_fields): 25 | """Create and save a SuperUser with the given email and password.""" 26 | extra_fields.setdefault('is_staff', True) 27 | extra_fields.setdefault('is_superuser', True) 28 | 29 | if extra_fields.get('is_staff') is not True: 30 | raise ValueError('Superuser must have is_staff=True.') 31 | if extra_fields.get('is_superuser') is not True: 32 | raise ValueError('Superuser must have is_superuser=True.') 33 | 34 | return self._create_user(email, password, **extra_fields) 35 | 36 | 37 | class CustomUser(AbstractUser): 38 | username = None 39 | email = models.EmailField(_('email address'), unique=True) 40 | 41 | USERNAME_FIELD = 'email' 42 | REQUIRED_FIELDS = [] 43 | 44 | objects = CustomUserManager() 45 | -------------------------------------------------------------------------------- /accounts/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 3.0.6 on 2020-05-26 06:31 2 | 3 | from django.db import migrations, models 4 | import django.utils.timezone 5 | 6 | 7 | class Migration(migrations.Migration): 8 | 9 | initial = True 10 | 11 | dependencies = [ 12 | ('auth', '0011_update_proxy_permissions'), 13 | ] 14 | 15 | operations = [ 16 | migrations.CreateModel( 17 | name='CustomUser', 18 | fields=[ 19 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 20 | ('password', models.CharField(max_length=128, verbose_name='password')), 21 | ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), 22 | ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), 23 | ('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')), 24 | ('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')), 25 | ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), 26 | ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), 27 | ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), 28 | ('email', models.EmailField(max_length=254, unique=True, verbose_name='email address')), 29 | ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')), 30 | ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')), 31 | ], 32 | options={ 33 | 'verbose_name': 'user', 34 | 'verbose_name_plural': 'users', 35 | 'abstract': False, 36 | }, 37 | ), 38 | ] 39 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.gitignore.io/api/django 3 | # Edit at https://www.gitignore.io/?templates=django 4 | 5 | ### Django ### 6 | *.log 7 | *.pot 8 | *.pyc 9 | __pycache__/ 10 | local_settings.py 11 | db.sqlite3 12 | db.sqlite3-journal 13 | media 14 | .idea/ 15 | 16 | # If your build process includes running collectstatic, then you probably don't need or want to include staticfiles/ 17 | # in your Git repository. Update and uncomment the following line accordingly. 18 | # /staticfiles/ 19 | 20 | ### Django.Python Stack ### 21 | # Byte-compiled / optimized / DLL files 22 | *.py[cod] 23 | *$py.class 24 | 25 | # C extensions 26 | *.so 27 | 28 | # Distribution / packaging 29 | .Python 30 | build/ 31 | develop-eggs/ 32 | dist/ 33 | downloads/ 34 | eggs/ 35 | .eggs/ 36 | lib/ 37 | lib64/ 38 | parts/ 39 | sdist/ 40 | var/ 41 | wheels/ 42 | pip-wheel-metadata/ 43 | share/python-wheels/ 44 | *.egg-info/ 45 | .installed.cfg 46 | *.egg 47 | MANIFEST 48 | 49 | # PyInstaller 50 | # Usually these files are written by a python script from a template 51 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 52 | *.manifest 53 | *.spec 54 | 55 | # Installer logs 56 | pip-log.txt 57 | pip-delete-this-directory.txt 58 | 59 | # Unit test / coverage reports 60 | htmlcov/ 61 | .tox/ 62 | .nox/ 63 | .coverage 64 | .coverage.* 65 | .cache 66 | nosetests.xml 67 | coverage.xml 68 | *.cover 69 | .hypothesis/ 70 | .pytest_cache/ 71 | 72 | # Translations 73 | *.mo 74 | 75 | # Scrapy stuff: 76 | .scrapy 77 | 78 | # Sphinx documentation 79 | docs/_build/ 80 | 81 | # PyBuilder 82 | target/ 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # celery beat schedule file 95 | celerybeat-schedule 96 | 97 | # SageMath parsed files 98 | *.sage.py 99 | 100 | # Spyder project settings 101 | .spyderproject 102 | .spyproject 103 | 104 | # Rope project settings 105 | .ropeproject 106 | 107 | # Mr Developer 108 | .mr.developer.cfg 109 | .project 110 | .pydevproject 111 | 112 | # mkdocs documentation 113 | /site 114 | 115 | # mypy 116 | .mypy_cache/ 117 | .dmypy.json 118 | dmypy.json 119 | 120 | # Pyre type checker 121 | .pyre/ 122 | 123 | # End of https://www.gitignore.io/api/django -------------------------------------------------------------------------------- /cb_dj_custom_user_model/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for cb_dj_custom_user_model project. 3 | 4 | Generated by 'django-admin startproject' using Django 3.0.6. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.0/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/3.0/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'ufaeoe_b0-t48h4#)dzbmo$cu=ehw274%9_u0$9c&b!casj7ig' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 'accounts', 41 | ] 42 | 43 | MIDDLEWARE = [ 44 | 'django.middleware.security.SecurityMiddleware', 45 | 'django.contrib.sessions.middleware.SessionMiddleware', 46 | 'django.middleware.common.CommonMiddleware', 47 | 'django.middleware.csrf.CsrfViewMiddleware', 48 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 49 | 'django.contrib.messages.middleware.MessageMiddleware', 50 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 51 | ] 52 | 53 | ROOT_URLCONF = 'cb_dj_custom_user_model.urls' 54 | 55 | TEMPLATES = [ 56 | { 57 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 58 | 'DIRS': [os.path.join(BASE_DIR, 'templates')], 59 | 'APP_DIRS': True, 60 | 'OPTIONS': { 61 | 'context_processors': [ 62 | 'django.template.context_processors.debug', 63 | 'django.template.context_processors.request', 64 | 'django.contrib.auth.context_processors.auth', 65 | 'django.contrib.messages.context_processors.messages', 66 | ], 67 | }, 68 | }, 69 | ] 70 | 71 | WSGI_APPLICATION = 'cb_dj_custom_user_model.wsgi.application' 72 | 73 | 74 | # Database 75 | # https://docs.djangoproject.com/en/3.0/ref/settings/#databases 76 | 77 | DATABASES = { 78 | 'default': { 79 | 'ENGINE': 'django.db.backends.sqlite3', 80 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 81 | } 82 | } 83 | 84 | 85 | # Password validation 86 | # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators 87 | 88 | AUTH_PASSWORD_VALIDATORS = [ 89 | { 90 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 91 | }, 92 | { 93 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 94 | }, 95 | { 96 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 97 | }, 98 | { 99 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 100 | }, 101 | ] 102 | 103 | 104 | # Internationalization 105 | # https://docs.djangoproject.com/en/3.0/topics/i18n/ 106 | 107 | LANGUAGE_CODE = 'en-us' 108 | 109 | TIME_ZONE = 'UTC' 110 | 111 | USE_I18N = True 112 | 113 | USE_L10N = True 114 | 115 | USE_TZ = True 116 | 117 | 118 | # Static files (CSS, JavaScript, Images) 119 | # https://docs.djangoproject.com/en/3.0/howto/static-files/ 120 | 121 | STATIC_URL = '/static/' 122 | 123 | AUTH_USER_MODEL = 'accounts.CustomUser' 124 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Custom User Model 2 | 3 | Custom User Model | [Authenticate with Email](#usage-authentication-with-email) | [Authenticate with Phone](#usage-authentication-with-phone) 4 | 5 | ## Usage (Authentication with Email) 6 | 7 | #### accounts/models.py 8 | ```python 9 | from django.contrib.auth.models import AbstractUser, BaseUserManager 10 | from django.db import models 11 | from django.utils.translation import gettext_lazy as _ 12 | 13 | 14 | class CustomUserManager(BaseUserManager): 15 | """Define a model manager for User model with no username field.""" 16 | 17 | def _create_user(self, email, password=None, **extra_fields): 18 | """Create and save a User with the given email and password.""" 19 | if not email: 20 | raise ValueError('The given email must be set') 21 | email = self.normalize_email(email) 22 | user = self.model(email=email, phone=phone, **extra_fields) 23 | user.set_password(password) 24 | user.save(using=self._db) 25 | return user 26 | 27 | def create_user(self, email, password=None, **extra_fields): 28 | extra_fields.setdefault('is_staff', False) 29 | extra_fields.setdefault('is_superuser', False) 30 | return self._create_user(email, password, **extra_fields) 31 | 32 | def create_superuser(self, email, password=None, **extra_fields): 33 | """Create and save a SuperUser with the given email and password.""" 34 | extra_fields.setdefault('is_staff', True) 35 | extra_fields.setdefault('is_superuser', True) 36 | 37 | if extra_fields.get('is_staff') is not True: 38 | raise ValueError('Superuser must have is_staff=True.') 39 | if extra_fields.get('is_superuser') is not True: 40 | raise ValueError('Superuser must have is_superuser=True.') 41 | 42 | return self._create_user(email, password, **extra_fields) 43 | 44 | 45 | class CustomUser(AbstractUser): 46 | username = None 47 | email = models.EmailField(_('email address'), unique=True) 48 | 49 | USERNAME_FIELD = 'email' 50 | REQUIRED_FIELDS = [] 51 | 52 | objects = CustomUserManager() 53 | ``` 54 | 55 | #### settings.py 56 | ```python 57 | AUTH_USER_MODEL = 'accounts.CustomUser' 58 | ``` 59 | 60 | #### accounts/admin.py 61 | ```python 62 | from django.contrib import admin 63 | from django.contrib.auth.admin import UserAdmin 64 | from django.utils.translation import gettext_lazy as _ 65 | from django.contrib.auth import get_user_model 66 | 67 | 68 | class CustomUserAdmin(UserAdmin): 69 | """Define admin model for custom User model with no username field.""" 70 | fieldsets = ( 71 | (None, {'fields': ('email', 'password')}), 72 | (_('Personal info'), {'fields': ('first_name', 'last_name')}), 73 | (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 74 | 'groups', 'user_permissions')}), 75 | (_('Important dates'), {'fields': ('last_login', 'date_joined')}), 76 | ) 77 | add_fieldsets = ( 78 | (None, { 79 | 'classes': ('wide',), 80 | 'fields': ('email', 'password1', 'password2'), 81 | }), 82 | ) 83 | list_display = ('email', 'first_name', 'last_name', 'is_staff') 84 | search_fields = ('email', 'first_name', 'last_name') 85 | ordering = ('email',) 86 | 87 | 88 | admin.site.register(get_user_model(), CustomUserAdmin) 89 | ``` 90 | 91 | #### forms.py 92 | ```python 93 | from django.contrib.auth import get_user_model 94 | from django.contrib.auth.forms import UserCreationForm 95 | 96 | 97 | class UserAdminCreationForm(UserCreationForm): 98 | """ 99 | A Custom form for creating new users. 100 | """ 101 | 102 | class Meta: 103 | model = get_user_model() 104 | fields = ['email'] 105 | ``` 106 | 107 | #### views.py 108 | ```python 109 | from django.shortcuts import render, redirect 110 | from accounts.forms import UserAdminCreationForm 111 | 112 | 113 | def register(req): 114 | form = UserAdminCreationForm() 115 | if req.method == 'POST': 116 | form = UserAdminCreationForm(req.POST) 117 | if form.is_valid(): 118 | form.save() 119 | return redirect('register') 120 | return render(req, 'register.html', {'form': form}) 121 | ``` 122 | 123 | #### urls.py 124 | ```python 125 | from django.contrib import admin 126 | from django.urls import path, include 127 | 128 | from accounts import views 129 | 130 | urlpatterns = [ 131 | path('admin/', admin.site.urls), 132 | path('register/', views.register, name='register'), 133 | path('accounts/', include('django.contrib.auth.urls')), 134 | ] 135 | ``` 136 | 137 | #### accounts/templates/admin/auth/user/add_form.html 138 | 139 | [Template](https://github.com/django/django/blob/master/django/contrib/admin/templates/admin/auth/user/add_form.html) 140 | 141 | ### accounts/templates/registration/login.html & accounts/templates/register.html 142 | 143 | ```html 144 |

145 | {% csrf_token %} 146 | {{ form.as_p }} 147 | 148 |
149 | ``` 150 | 151 | --- 152 | ## Usage (Authentication with Phone) 153 | 154 | (Best way to store phone number is using [PhoneNumberField](https://pypi.org/project/django-phonenumber-field)) 155 | 156 | #### accounts/models.py 157 | ```python 158 | from django.contrib.auth.models import AbstractUser, BaseUserManager 159 | from django.db import models 160 | from django.utils.translation import gettext_lazy as _ 161 | 162 | 163 | class CustomUserManager(BaseUserManager): 164 | """Define a model manager for User model with no username field.""" 165 | 166 | def _create_user(self, phone, password=None, **extra_fields): 167 | """Create and save a User with the given phone and password.""" 168 | if not phone: 169 | raise ValueError('The given phone must be set') 170 | user = self.model(phone=phone, **extra_fields) 171 | user.set_password(password) 172 | user.save(using=self._db) 173 | return user 174 | 175 | def create_user(self, phone, password=None, **extra_fields): 176 | extra_fields.setdefault('is_staff', False) 177 | extra_fields.setdefault('is_superuser', False) 178 | return self._create_user(phone, password, **extra_fields) 179 | 180 | def create_superuser(self, phone, password=None, **extra_fields): 181 | """Create and save a SuperUser with the given phone and password.""" 182 | extra_fields.setdefault('is_staff', True) 183 | extra_fields.setdefault('is_superuser', True) 184 | 185 | if extra_fields.get('is_staff') is not True: 186 | raise ValueError('Superuser must have is_staff=True.') 187 | if extra_fields.get('is_superuser') is not True: 188 | raise ValueError('Superuser must have is_superuser=True.') 189 | 190 | return self._create_user(phone, password, **extra_fields) 191 | 192 | 193 | class CustomUser(AbstractUser): 194 | username = None 195 | phone = IntegerField(max_length=10, unique=True, verbose_name='Phone Number', blank=False, help_text='Enter 10 digits phone number') 196 | 197 | USERNAME_FIELD = 'phone' 198 | REQUIRED_FIELDS = [] 199 | 200 | objects = CustomUserManager() 201 | ``` 202 | 203 | #### settings.py 204 | ```python 205 | AUTH_USER_MODEL = 'accounts.CustomUser' 206 | ``` 207 | 208 | #### accounts/admin.py 209 | ```python 210 | from django.contrib import admin 211 | from django.contrib.auth.admin import UserAdmin 212 | from django.utils.translation import gettext_lazy as _ 213 | from django.contrib.auth import get_user_model 214 | 215 | 216 | class CustomUserAdmin(UserAdmin): 217 | """Define admin model for custom User model with no username field.""" 218 | fieldsets = ( 219 | (None, {'fields': ('phone', 'password')}), 220 | (_('Personal info'), {'fields': ('first_name', 'last_name')}), 221 | (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 222 | 'groups', 'user_permissions')}), 223 | (_('Important dates'), {'fields': ('last_login', 'date_joined')}), 224 | ) 225 | add_fieldsets = ( 226 | (None, { 227 | 'classes': ('wide',), 228 | 'fields': ('phone', 'password1', 'password2'), 229 | }), 230 | ) 231 | list_display = ('phone', 'first_name', 'last_name', 'is_staff') 232 | search_fields = ('phone', 'first_name', 'last_name') 233 | ordering = ('phone',) 234 | 235 | 236 | admin.site.register(get_user_model(), CustomUserAdmin) 237 | ``` 238 | 239 | #### forms.py 240 | ```python 241 | from django.contrib.auth import get_user_model 242 | from django.contrib.auth.forms import UserCreationForm 243 | 244 | 245 | class UserAdminCreationForm(UserCreationForm): 246 | """ 247 | A Custom form for creating new users. 248 | """ 249 | 250 | class Meta: 251 | model = get_user_model() 252 | fields = ['phone'] 253 | ``` 254 | 255 | #### views.py 256 | ```python 257 | from django.shortcuts import render, redirect 258 | from accounts.forms import UserAdminCreationForm 259 | 260 | 261 | def register(req): 262 | form = UserAdminCreationForm() 263 | if req.method == 'POST': 264 | form = UserAdminCreationForm(req.POST) 265 | if form.is_valid(): 266 | form.save() 267 | return redirect('register') 268 | return render(req, 'register.html', {'form': form}) 269 | ``` 270 | 271 | #### urls.py 272 | ```python 273 | from django.contrib import admin 274 | from django.urls import path, include 275 | 276 | from accounts import views 277 | 278 | urlpatterns = [ 279 | path('admin/', admin.site.urls), 280 | path('register/', views.register, name='register'), 281 | path('accounts/', include('django.contrib.auth.urls')), 282 | ] 283 | ``` 284 | 285 | #### accounts/templates/admin/auth/user/add_form.html 286 | 287 | [Template](https://github.com/django/django/blob/master/django/contrib/admin/templates/admin/auth/user/add_form.html) 288 | 289 | ### accounts/templates/registration/login.html & accounts/templates/register.html 290 | 291 | ```html 292 |
293 | {% csrf_token %} 294 | {{ form.as_p }} 295 | 296 |
297 | ``` 298 | --------------------------------------------------------------------------------