├── backend ├── __init__.py ├── accounts │ ├── __init__.py │ ├── migrations │ │ ├── __init__.py │ │ └── 0001_initial.py │ ├── views.py │ ├── templates │ │ └── accounts │ │ │ └── profile.html │ ├── apps.py │ ├── urls.py │ ├── managers.py │ ├── admin.py │ ├── tests.py │ └── models.py ├── core │ ├── __init__.py │ ├── migrations │ │ └── __init__.py │ ├── apps.py │ ├── views.py │ ├── urls.py │ ├── templates │ │ ├── index.html │ │ └── base.html │ └── static │ │ └── css │ │ └── custom.css ├── urls.py ├── asgi.py ├── wsgi.py └── settings.py ├── img ├── index.png ├── mailhog.png └── youtube.png ├── requirements.txt ├── manage.py ├── contrib └── env_gen.py ├── docker-compose.yml ├── .gitignore └── README.md /backend/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /backend/accounts/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /backend/core/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /backend/core/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /backend/accounts/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /img/index.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rg3915/django-custom-user-email-with-django-registration-redux/main/img/index.png -------------------------------------------------------------------------------- /img/mailhog.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rg3915/django-custom-user-email-with-django-registration-redux/main/img/mailhog.png -------------------------------------------------------------------------------- /img/youtube.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rg3915/django-custom-user-email-with-django-registration-redux/main/img/youtube.png -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | Django==5.0.6 2 | django-extensions==3.2.3 3 | django-registration-redux==2.13 4 | python-decouple==3.8 5 | psycopg2-binary==2.9.9 6 | -------------------------------------------------------------------------------- /backend/core/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class CoreConfig(AppConfig): 5 | default_auto_field = 'django.db.models.BigAutoField' 6 | name = 'backend.core' 7 | -------------------------------------------------------------------------------- /backend/accounts/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | 3 | 4 | def profile(request): 5 | template_name = 'accounts/profile.html' 6 | return render(request, template_name) 7 | -------------------------------------------------------------------------------- /backend/accounts/templates/accounts/profile.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block content %} 4 |

Perfil

5 | 6 |

e-mail: {{ request.user }}

7 | {% endblock content %} 8 | -------------------------------------------------------------------------------- /backend/accounts/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class AccountsConfig(AppConfig): 5 | default_auto_field = 'django.db.models.BigAutoField' 6 | name = 'backend.accounts' 7 | -------------------------------------------------------------------------------- /backend/core/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | 3 | 4 | def index(request): 5 | template_name = 'index.html' 6 | context = {} 7 | return render(request, template_name, context) 8 | -------------------------------------------------------------------------------- /backend/core/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path 2 | 3 | from backend.core import views as v 4 | 5 | app_name = 'core' 6 | 7 | 8 | urlpatterns = [ 9 | path('', v.index, name='index'), 10 | ] 11 | -------------------------------------------------------------------------------- /backend/urls.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from django.urls import include, path 3 | 4 | 5 | urlpatterns = [ 6 | path('', include('backend.core.urls', namespace='core')), 7 | path('accounts/', include('backend.accounts.urls')), # without namespace 8 | path('accounts/', include('registration.backends.default.urls')), # django-registration-redux 9 | path('admin/', admin.site.urls), 10 | ] 11 | -------------------------------------------------------------------------------- /backend/accounts/urls.py: -------------------------------------------------------------------------------- 1 | # from django.contrib.auth.views import LoginView, LogoutView 2 | from django.urls import path 3 | 4 | from .views import profile 5 | 6 | # Read https://github.com/rg3915/django-auth-tutorial 7 | 8 | 9 | urlpatterns = [ 10 | # path('login/', LoginView.as_view(), name='login'), 11 | # path('logout/', LogoutView.as_view(), name='logout'), 12 | path('profile/', profile, name='profile'), 13 | ] 14 | -------------------------------------------------------------------------------- /backend/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for backend 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/5.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', 'backend.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /backend/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for backend 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/5.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', 'backend.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /backend/core/templates/index.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block content %} 4 |
5 |
6 |
7 |

Custom User E-mail and Django Registration Redux

8 |
9 |

10 | Django com usuário customizado para fazer login com email. 11 |

12 | 13 | Login 18 |
19 |
20 | {% endblock content %} -------------------------------------------------------------------------------- /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 | """Run administrative tasks.""" 9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings') 10 | try: 11 | from django.core.management import execute_from_command_line 12 | except ImportError as exc: 13 | raise ImportError( 14 | "Couldn't import Django. Are you sure it's installed and " 15 | "available on your PYTHONPATH environment variable? Did you " 16 | "forget to activate a virtual environment?" 17 | ) from exc 18 | execute_from_command_line(sys.argv) 19 | 20 | 21 | if __name__ == '__main__': 22 | main() 23 | -------------------------------------------------------------------------------- /contrib/env_gen.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python SECRET_KEY generator. 3 | """ 4 | import random 5 | 6 | chars = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!?@#$%^&*()" 7 | size = 50 8 | secret_key = "".join(random.sample(chars, size)) 9 | 10 | chars = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!?@#$%_" 11 | size = 20 12 | password = "".join(random.sample(chars, size)) 13 | 14 | CONFIG_STRING = """ 15 | DEBUG=True 16 | SECRET_KEY=%s 17 | ALLOWED_HOSTS=127.0.0.1,.localhost,0.0.0.0 18 | 19 | #DATABASE_URL=postgres://USER:PASSWORD@HOST:PORT/NAME 20 | #POSTGRES_DB= 21 | #POSTGRES_USER= 22 | #POSTGRES_PASSWORD=%s 23 | #DB_HOST=localhost 24 | 25 | #DEFAULT_FROM_EMAIL= 26 | #EMAIL_BACKEND=django.core.mail.backends.smtp.EmailBackend 27 | #EMAIL_HOST=localhost 28 | #EMAIL_PORT= 29 | #EMAIL_HOST_USER= 30 | #EMAIL_HOST_PASSWORD= 31 | #EMAIL_USE_TLS=True 32 | """.strip() % (secret_key, password) 33 | 34 | # Writing our configuration file to '.env' 35 | with open('.env', 'w') as configfile: 36 | configfile.write(CONFIG_STRING) 37 | 38 | print('Success!') 39 | print('Type: cat .env') 40 | -------------------------------------------------------------------------------- /backend/accounts/managers.py: -------------------------------------------------------------------------------- 1 | from django.contrib.auth.base_user import BaseUserManager 2 | 3 | 4 | class UserManager(BaseUserManager): 5 | use_in_migrations = True 6 | 7 | def _create_user(self, email, password, **extra_fields): 8 | """ 9 | Creates and saves a User with the given email and password. 10 | """ 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_superuser', False) 21 | return self._create_user(email, password, **extra_fields) 22 | 23 | def create_superuser(self, email, password, **extra_fields): 24 | extra_fields.setdefault('is_admin', True) 25 | extra_fields.setdefault('is_superuser', True) 26 | 27 | if extra_fields.get('is_admin') is not True: 28 | raise ValueError('Superuser must have is_admin=True.') 29 | if extra_fields.get('is_superuser') is not True: 30 | raise ValueError('Superuser must have is_superuser=True.') 31 | 32 | return self._create_user(email, password, **extra_fields) 33 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.8" 2 | 3 | services: 4 | db: 5 | container_name: django_registration_db 6 | image: postgres:14-alpine 7 | restart: always 8 | user: postgres # importante definir o usuário 9 | volumes: 10 | - pgdata:/var/lib/postgresql/data 11 | environment: 12 | - LC_ALL=C.UTF-8 13 | - POSTGRES_PASSWORD=postgres # senha padrão 14 | - POSTGRES_USER=postgres # usuário padrão 15 | - POSTGRES_DB=django_db # necessário porque foi configurado assim no settings 16 | ports: 17 | - 5431:5432 # repare na porta externa 5431 18 | networks: 19 | - django-registration-network 20 | 21 | pgadmin: 22 | container_name: django_registration_pgadmin 23 | image: dpage/pgadmin4 24 | restart: unless-stopped 25 | volumes: 26 | - pgadmin:/var/lib/pgadmin 27 | environment: 28 | PGADMIN_DEFAULT_EMAIL: admin@admin.com 29 | PGADMIN_DEFAULT_PASSWORD: admin 30 | PGADMIN_CONFIG_SERVER_MODE: 'False' 31 | ports: 32 | - 5051:80 33 | networks: 34 | - django-registration-network 35 | 36 | mailhog: 37 | container_name: django_registration_mailhog 38 | image: mailhog/mailhog 39 | restart: always 40 | logging: 41 | driver: 'none' 42 | ports: 43 | - 1025:1025 44 | - 8025:8025 45 | networks: 46 | - django-registration-network 47 | 48 | volumes: 49 | pgdata: # mesmo nome do volume externo definido na linha 10 50 | pgadmin: 51 | 52 | networks: 53 | django-registration-network: 54 | -------------------------------------------------------------------------------- /backend/accounts/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from django.contrib.auth.admin import UserAdmin as BaseUserAdmin 3 | from django.utils.translation import gettext_lazy as _ 4 | 5 | from .models import User 6 | 7 | 8 | class UserAdmin(BaseUserAdmin): 9 | # The fields to be used in displaying the User model. 10 | # These override the definitions on the base UserAdmin 11 | # that reference specific fields on auth.User. 12 | list_display = ('email', 'first_name', 'last_name', 'is_admin') 13 | list_filter = ('is_admin',) 14 | fieldsets = ( 15 | (None, {'fields': ('email', 'password')}), 16 | (_('Personal info'), {'fields': ('first_name', 'last_name')}), 17 | (_('Permissions'), { 18 | 'fields': ( 19 | 'is_active', 20 | 'is_admin', 21 | # 'is_superuser', 22 | 'groups', 23 | 'user_permissions', 24 | ) 25 | }), 26 | (_('Important dates'), {'fields': ('last_login',)}), 27 | ) 28 | # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin 29 | # overrides get_fieldsets to use this attribute when creating a user. 30 | add_fieldsets = ( 31 | (None, { 32 | 'classes': ('wide',), 33 | 'fields': ('email', 'password1', 'password2'), 34 | }), 35 | ) 36 | search_fields = ('email', 'first_name', 'last_name') 37 | ordering = ('email',) 38 | filter_horizontal = ('groups', 'user_permissions',) 39 | 40 | 41 | admin.site.register(User, UserAdmin) 42 | -------------------------------------------------------------------------------- /backend/core/static/css/custom.css: -------------------------------------------------------------------------------- 1 | /* Global CSS variables */ 2 | :root { 3 | --spacing-company: 3rem; 4 | --font-weight: 400; 5 | } 6 | 7 | /* Typography */ 8 | h2, 9 | h3, 10 | hgroup> :last-child { 11 | font-weight: 200; 12 | } 13 | 14 | small { 15 | color: var(--muted-color); 16 | } 17 | 18 | /* Header */ 19 | .hero { 20 | background-color: #394046; 21 | background-image: url("https://images.unsplash.com/photo-1544668637-89001ab6415e?q=80&w=1673&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D"); 22 | background-position: center; 23 | background-size: cover; 24 | } 25 | 26 | header { 27 | padding: var(--spacing-company) 0; 28 | } 29 | 30 | header hgroup> :last-child { 31 | color: var(--h3-color); 32 | } 33 | 34 | header hgroup { 35 | margin-bottom: var(--spacing-company); 36 | } 37 | 38 | /* Nav */ 39 | summary[role="link"].contrast:is([aria-current], :hover, :active, :focus) { 40 | background-color: transparent; 41 | color: var(--contrast-hover); 42 | } 43 | 44 | form.grid { 45 | grid-row-gap: 0; 46 | } 47 | 48 | .mb-0 { 49 | margin-bottom: 0 !important; 50 | } 51 | 52 | /* Aside nav */ 53 | aside img { 54 | margin-bottom: 0.25rem; 55 | } 56 | 57 | aside p { 58 | margin-bottom: var(--spacing-company); 59 | line-height: 1.25; 60 | } 61 | 62 | dialog article { 63 | width: 700px; 64 | } 65 | 66 | .ml-2 { 67 | margin-left: 1rem; 68 | } 69 | 70 | .mb-2 { 71 | margin-bottom: 1rem; 72 | } 73 | 74 | .is-danger { 75 | color: red; 76 | } 77 | 78 | .text-center { 79 | text-align: center; 80 | } -------------------------------------------------------------------------------- /backend/accounts/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | from backend.accounts.models import User 4 | 5 | 6 | class TestUser(TestCase): 7 | def setUp(self): 8 | self.user = User.objects.create_user( 9 | email='admin@email.com', 10 | password='demodemo', 11 | first_name='Admin', 12 | last_name='Admin', 13 | ) 14 | self.superuser = User.objects.create_superuser( 15 | email='superadmin@email.com', 16 | password='demodemo' 17 | ) 18 | 19 | def test_user_exists(self): 20 | self.assertTrue(self.user) 21 | 22 | def test_str(self): 23 | self.assertEqual(self.user.email, 'admin@email.com') 24 | 25 | def test_return_attributes(self): 26 | fields = ( 27 | 'id', 28 | 'email', 29 | 'first_name', 30 | 'last_name', 31 | 'password', 32 | 'is_active', 33 | 'is_admin', 34 | 'is_superuser', 35 | 'date_joined', 36 | 'last_login', 37 | ) 38 | 39 | for field in fields: 40 | with self.subTest(): 41 | self.assertTrue(hasattr(User, field)) 42 | 43 | def test_user_is_authenticated(self): 44 | self.assertTrue(self.user.is_authenticated) 45 | 46 | def test_user_is_active(self): 47 | self.assertTrue(self.user.is_active) 48 | 49 | def test_user_is_staff(self): 50 | self.assertFalse(self.user.is_staff) 51 | 52 | def test_user_is_superuser(self): 53 | self.assertFalse(self.user.is_superuser) 54 | 55 | def test_superuser_is_superuser(self): 56 | self.assertTrue(self.superuser.is_superuser) 57 | 58 | def test_user_has_perm(self): 59 | self.assertTrue(self.user.has_perm) 60 | 61 | def test_user_has_module_perms(self): 62 | self.assertTrue(self.user.has_module_perms) 63 | 64 | def test_user_get_full_name(self): 65 | self.assertEqual(self.user.get_full_name(), 'Admin Admin') 66 | 67 | def test_user_get_short_name(self): 68 | self.assertEqual(self.user.get_short_name(), 'Admin') 69 | -------------------------------------------------------------------------------- /backend/accounts/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 5.0.6 on 2024-06-09 01:01 2 | 3 | import backend.accounts.managers 4 | from django.db import migrations, models 5 | 6 | 7 | class Migration(migrations.Migration): 8 | 9 | initial = True 10 | 11 | dependencies = [ 12 | ('auth', '0012_alter_user_first_name_max_length'), 13 | ] 14 | 15 | operations = [ 16 | migrations.CreateModel( 17 | name='User', 18 | fields=[ 19 | ('id', models.BigAutoField(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 | ('email', models.EmailField(max_length=254, unique=True, verbose_name='email address')), 24 | ('first_name', models.CharField(blank=True, max_length=150, verbose_name='first name')), 25 | ('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')), 26 | ('date_joined', models.DateTimeField(auto_now_add=True, verbose_name='date joined')), 27 | ('is_active', models.BooleanField(default=True, verbose_name='active')), 28 | ('is_admin', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='admin status')), 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 | }, 36 | managers=[ 37 | ('objects', backend.accounts.managers.UserManager()), 38 | ], 39 | ), 40 | ] 41 | -------------------------------------------------------------------------------- /backend/accounts/models.py: -------------------------------------------------------------------------------- 1 | from __future__ import unicode_literals 2 | 3 | from django.contrib.auth.base_user import AbstractBaseUser 4 | from django.contrib.auth.models import PermissionsMixin 5 | from django.core.mail import send_mail 6 | from django.db import models 7 | from django.utils.translation import gettext_lazy as _ 8 | 9 | from .managers import UserManager 10 | 11 | 12 | class User(AbstractBaseUser, PermissionsMixin): 13 | email = models.EmailField(_('email address'), unique=True) 14 | first_name = models.CharField(_('first name'), max_length=150, blank=True) 15 | last_name = models.CharField(_('last name'), max_length=150, blank=True) 16 | date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) 17 | is_active = models.BooleanField(_('active'), default=True) 18 | is_admin = models.BooleanField( 19 | _('admin status'), 20 | default=False, 21 | help_text=_( 22 | 'Designates whether the user can log into this admin site.'), 23 | ) 24 | 25 | objects = UserManager() 26 | 27 | USERNAME_FIELD = 'email' 28 | REQUIRED_FIELDS = [] 29 | 30 | class Meta: 31 | verbose_name = _('user') 32 | verbose_name_plural = _('users') 33 | 34 | def __str__(self): 35 | return self.email 36 | 37 | def has_perm(self, perm, obj=None): 38 | "Does the user have a specific permission?" 39 | # Simplest possible answer: Yes, always 40 | return True 41 | 42 | def has_module_perms(self, app_label): 43 | "Does the user have permissions to view the app `app_label`?" 44 | # Simplest possible answer: Yes, always 45 | return True 46 | 47 | def get_full_name(self): 48 | ''' 49 | Returns the first_name plus the last_name, with a space in between. 50 | ''' 51 | full_name = '%s %s' % (self.first_name, self.last_name) 52 | return full_name.strip() 53 | 54 | def get_short_name(self): 55 | ''' 56 | Returns the short name for the user. 57 | ''' 58 | return self.first_name 59 | 60 | def email_user(self, subject, message, from_email=None, **kwargs): 61 | ''' 62 | Sends an email to this User. 63 | ''' 64 | send_mail(subject, message, from_email, [self.email], **kwargs) 65 | 66 | @property 67 | def is_staff(self): 68 | "Is the user a member of staff?" 69 | # Simplest possible answer: All admins are staff 70 | return self.is_admin 71 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 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 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | 131 | .DS_Store 132 | 133 | media/ 134 | staticfiles/ 135 | .idea 136 | .ipynb_checkpoints/ 137 | .vscode 138 | *.cast 139 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # django-custom-user-email-with-django-registration-redux 2 | 3 | Django com usuário customizado para fazer login com email. 4 | 5 | E usa [django-registration-redux](https://django-registration-redux.readthedocs.io/en/latest/) para fazer o gerenciamento de login, reset de senha, entre outros. 6 | 7 | 8 | **Github:** https://github.com/macropin/django-registration 9 | 10 | **Doc:** https://django-registration-redux.readthedocs.io/en/latest/ 11 | 12 | ![](img/index.png) 13 | 14 | 15 | ## Este projeto foi feito com: 16 | 17 | * [Django 5.0.6](https://www.djangoproject.com/) 18 | * [django-registration-redux](https://django-registration-redux.readthedocs.io/en/latest/) 19 | 20 | ## Instalação 21 | 22 | * Clone esse repositório. 23 | * Crie um virtualenv com Python 3. 24 | * Ative o virtualenv. 25 | * Instale as dependências. 26 | * Rode as migrações. 27 | 28 | ``` 29 | git clone https://github.com/rg3915/django-custom-user-email-with-django-registration-redux.git 30 | cd django-custom-user-email-with-django-registration-redux 31 | 32 | python -m venv .venv 33 | source .venv/bin/activate 34 | 35 | pip install -r requirements.txt 36 | 37 | docker-compose up -d 38 | 39 | python contrib/env_gen.py 40 | 41 | python manage.py migrate 42 | python manage.py createsuperuser --username="admin" --email="" 43 | 44 | python manage.py test 45 | 46 | python manage.py runserver 47 | ``` 48 | 49 | ## models.py 50 | 51 | ```python 52 | # accounts/models.py 53 | class User(AbstractBaseUser, PermissionsMixin): 54 | email = models.EmailField(_('email address'), unique=True) 55 | first_name = models.CharField(_('first name'), max_length=150, blank=True) 56 | last_name = models.CharField(_('last name'), max_length=150, blank=True) 57 | date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) 58 | is_active = models.BooleanField(_('active'), default=True) 59 | is_admin = models.BooleanField( 60 | _('admin status'), 61 | default=False, 62 | help_text=_( 63 | 'Designates whether the user can log into this admin site.'), 64 | ) 65 | 66 | objects = UserManager() 67 | 68 | USERNAME_FIELD = 'email' 69 | REQUIRED_FIELDS = [] 70 | 71 | class Meta: 72 | verbose_name = _('user') 73 | verbose_name_plural = _('users') 74 | 75 | def __str__(self): 76 | return self.email 77 | ``` 78 | 79 | ## Mailhog 80 | 81 | Acesse os e-mails em http://localhost:8025 82 | 83 | ![](img/mailhog.png) 84 | 85 | --- 86 | 87 | Baseado em [django-custom-login-email](https://github.com/rg3915/django-custom-login-email) 88 | 89 | 90 | 91 | 92 | -------------------------------------------------------------------------------- /backend/core/templates/base.html: -------------------------------------------------------------------------------- 1 | {% load static %} 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | Django Custom User 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 |
28 | 54 |
55 |
56 |

Custom User E-mail and Django Registration Redux

57 |
58 |

Github

63 |

Imagem by Unsplash

64 |
65 |
66 | 67 | 68 | 69 |
70 | {% block content %}{% endblock content %} 71 |
72 | 73 | 74 | 75 | 79 | 80 | 81 | {% block js %}{% endblock js %} 82 | 83 | 84 | -------------------------------------------------------------------------------- /backend/settings.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | 3 | from decouple import config, Csv 4 | 5 | 6 | BASE_DIR = Path(__file__).resolve().parent.parent 7 | 8 | # SECURITY WARNING: keep the secret key used in production secret! 9 | SECRET_KEY = config('SECRET_KEY') 10 | 11 | # SECURITY WARNING: don't run with debug turned on in production! 12 | DEBUG = config('DEBUG', default=False, cast=bool) 13 | 14 | ALLOWED_HOSTS = config('ALLOWED_HOSTS', default=[], cast=Csv()) 15 | 16 | AUTH_USER_MODEL = 'accounts.User' 17 | 18 | INSTALLED_APPS = [ 19 | 'backend.accounts', # <--- 20 | 'registration', # <--- 21 | 'django.contrib.admin', 22 | 'django.contrib.auth', 23 | 'django.contrib.contenttypes', 24 | 'django.contrib.sessions', 25 | 'django.contrib.messages', 26 | 'django.contrib.staticfiles', 27 | # others apps 28 | 'django_extensions', 29 | # my apps 30 | 'backend.core', 31 | ] 32 | 33 | REGISTRATION_AUTO_LOGIN = True 34 | 35 | ACCOUNT_ACTIVATION_DAYS = 3 36 | 37 | MIDDLEWARE = [ 38 | 'django.middleware.security.SecurityMiddleware', 39 | 'django.contrib.sessions.middleware.SessionMiddleware', 40 | 'django.middleware.common.CommonMiddleware', 41 | 'django.middleware.csrf.CsrfViewMiddleware', 42 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 43 | 'django.contrib.messages.middleware.MessageMiddleware', 44 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 45 | ] 46 | 47 | ROOT_URLCONF = 'backend.urls' 48 | 49 | TEMPLATES = [ 50 | { 51 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 52 | 'DIRS': [], 53 | 'APP_DIRS': True, 54 | 'OPTIONS': { 55 | 'context_processors': [ 56 | 'django.template.context_processors.debug', 57 | 'django.template.context_processors.request', 58 | 'django.contrib.auth.context_processors.auth', 59 | 'django.contrib.messages.context_processors.messages', 60 | ], 61 | }, 62 | }, 63 | ] 64 | 65 | WSGI_APPLICATION = 'backend.wsgi.application' 66 | 67 | 68 | # Database 69 | # https://docs.djangoproject.com/en/5.0/ref/settings/#databases 70 | 71 | # DATABASES = { 72 | # 'default': { 73 | # 'ENGINE': 'django.db.backends.sqlite3', 74 | # 'NAME': BASE_DIR / 'db.sqlite3', 75 | # } 76 | # } 77 | 78 | DATABASES = { 79 | 'default': { 80 | 'ENGINE': 'django.db.backends.postgresql', 81 | 'NAME': config('POSTGRES_DB', 'django_db'), 82 | 'USER': config('POSTGRES_USER', 'postgres'), 83 | 'PASSWORD': config('POSTGRES_PASSWORD', 'postgres'), 84 | 'HOST': config('DB_HOST', 'localhost'), 85 | 'PORT': config('DB_PORT', 5431, cast=int), 86 | } 87 | } 88 | 89 | # Email config 90 | EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' 91 | 92 | DEFAULT_FROM_EMAIL = config('DEFAULT_FROM_EMAIL', 'webmaster@localhost') 93 | EMAIL_HOST = config('EMAIL_HOST', 'localhost') 94 | EMAIL_PORT = config('EMAIL_PORT', 1025, cast=int) 95 | EMAIL_HOST_USER = config('EMAIL_HOST_USER', '') 96 | EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD', '') 97 | EMAIL_USE_TLS = config('EMAIL_USE_TLS', default=False, cast=bool) 98 | 99 | 100 | # Password validation 101 | # https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators 102 | 103 | AUTH_PASSWORD_VALIDATORS = [ 104 | { 105 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 106 | }, 107 | { 108 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 109 | }, 110 | { 111 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 112 | }, 113 | { 114 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 115 | }, 116 | ] 117 | 118 | 119 | # Internationalization 120 | # https://docs.djangoproject.com/en/5.0/topics/i18n/ 121 | 122 | LANGUAGE_CODE = 'pt-br' 123 | 124 | TIME_ZONE = 'America/Sao_Paulo' 125 | 126 | USE_I18N = True 127 | 128 | USE_TZ = True 129 | 130 | 131 | # Static files (CSS, JavaScript, Images) 132 | # https://docs.djangoproject.com/en/5.0/howto/static-files/ 133 | 134 | STATIC_URL = 'static/' 135 | STATIC_ROOT = BASE_DIR.joinpath('staticfiles') 136 | 137 | # Default primary key field type 138 | # https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field 139 | 140 | DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' 141 | 142 | # Comente esta linha caso queira ir para a página default: /accounts/profile/ 143 | # LOGIN_REDIRECT_URL = 'core:index' 144 | --------------------------------------------------------------------------------