User model, campos requeridos, superusuario, admin

This commit is contained in:
devfzn 2023-10-07 16:36:13 -03:00
parent ca9ca658c7
commit d035ec4cca
Signed by: devfzn
GPG Key ID: E070ECF4A754FDB1
21 changed files with 729 additions and 14 deletions

520
README.md
View File

@ -130,8 +130,8 @@ RF --> RTP
- Mapeo de puertos - Mapeo de puertos
- Mapeo de volumenes - Mapeo de volumenes
- Correr todos los comandos a travez de Docker Compose - Correr todos los comandos a travez de Docker Compose
ej. `docker-compose run --rm app sh -c "python manage.py collectstatic"` ej. `docker compose run --rm app sh -c "python manage.py collectstatic"`
- `docker-compose` Ejecuta un comando de Docker Compose - `docker compose` Ejecuta un comando de Docker Compose
- `run` comienza un contenedor específico definido en la configuración - `run` comienza un contenedor específico definido en la configuración
- `--rm` remueve el contenedor - `--rm` remueve el contenedor
- `app` es el nombre del servicio/aplicación - `app` es el nombre del servicio/aplicación
@ -150,7 +150,7 @@ docker build .
- [docker-compose.yml](./docker-compose.yml) - [docker-compose.yml](./docker-compose.yml)
```sh ```sh
docker-compose build docker compose build
``` ```
### Linting ### Linting
@ -158,25 +158,25 @@ docker-compose build
- Instalar `flake8` - Instalar `flake8`
- [requirements.dev.txt](./requirements.dev.txt) - [requirements.dev.txt](./requirements.dev.txt)
- Configuración [flake8](./app/.flake8) - Configuración [flake8](./app/.flake8)
- Correr a travez de docker-compose `docker-compose run --rm app sh -c "flake8"` - Correr a travez de docker compose `docker compose run --rm app sh -c "flake8"`
### Testing ### Testing
- Django test suite - Django test suite
- Configurar test por cada aplicación Django - Configurar test por cada aplicación Django
- Correr a travez de docker-compose `docker-compose run --rm app sh -c "python - Correr a travez de docker compose `docker compose run --rm app sh -c "python
manage.py test"` manage.py test"`
### Creación del proyecto Django ### Creación del proyecto Django
```sh ```sh
docker-compose run -rm app sh -c "django-admin startproject app ." docker compose run -rm app sh -c "django-admin startproject app ."
``` ```
### Iniciar el servidor ### Iniciar el servidor
```sh ```sh
docker-compose up docker compose up
``` ```
### GitHub Actions ### GitHub Actions
@ -767,7 +767,7 @@ class Ingredient(models.Model):
### Creación de las migraciones ### Creación de las migraciones
- Asegura que la app esta activa en `settings.py` - Asegura que la app esta activa en `settings.py`
- Se utiliza el CLI de DJango `python manage.py makemigrations` - Se utiliza el CLI de Django `python manage.py makemigrations`
- Aplicar migraciones `python manage.py makemigrations` - Aplicar migraciones `python manage.py makemigrations`
- Correr despues de esperar por la base de datos - Correr despues de esperar por la base de datos
@ -805,3 +805,507 @@ class Ingredient(models.Model):
python manage.py test" python manage.py test"
... ...
``` ```
## User Model
### Autenticación Django
- Sistema de autenticación *built-in*
- Framework para características básicas
- Registro
- Login
- Autorización
- Se integran con el panel de administración de Django
### Django user model
- Es la fundación del sistema de autenticación de Django
- Django incorpora por defecto un modelo de usuario
- Utiliza un nombre de usuario en vez de un email
- No es facil de personalizar
- Creación de modelo de usuario personalizado para nuevos proyectos
- Permite el uso de email en vz de nombre de usuario
- Asegura compatibilidad del proyecto con posibles cambios del modelo usuario
en versiones futuras
### Creación del modelo
- Basado en la clase `AbstractBaseUser` y `PermissionsMixin`
- Creación de administrador personalizado
- Se establece `AUTH_USER_MODEL` en `settings.py` para utlizar este modelo
- Creación y ejecución de las migraciones
### AbstractBaseUser
- Proporciona las características de autenticación
- No incluye campos
### PermissionsMixin
- Soporte para el sistema de permisos de Django
- Incuye todos los campos y métodos necesarios
### Problemas comunes
- Correr migraciones antes de crear el modelo personalizado
- Crear el modelo personalizado primero
- Tipeo
- Indentación
## User Model personalizado
### Campos de usuario
- email `EmailField`
- name `CharField`
- is_active `BooleanField`
- is_staff `BooleanField`
### User Model administrador
- Usado para administar objetos
- Lógica personalizada para crear objetos
- **Hash** passwords
- Metodos para el CLI de Django
- Create superuser
### BaseUserManager
- Clase base para administrar usuarios
- Métodos útliles de ayuda
- `normalize_email` para almacenar emails de forma consistente
- Métodos a definir
- `create_user` llamado al crear usuarios
- `create_superuser` usado por el CLI para crear un super usuario (**admin**)
### Agregando Unitetst para el modelo usuario personalizado
[test_models.py](./app/core/tests/tests_models.py)
```py
from django.test import TestCase
from django.contrib.auth import get_user_model
class ModelTests(TestCase):
def test_create_user_with_email_sucessfull(self):
email = 'test@example.com'
password = 'testpass123'
user = get_user_model().objects.create_user(
email=email,
password=password,
)
self.assertEqual(user.email, email)
self.assertTrue(user.check_password(password))
```
### Agregar usuario personalizado al proyecto
[models.py](./app/core/models.py)
```py
from django.db import models
from django.contrib.auth.models import (
AbstractBaseUser,
BaseUserManager,
PermissionsMixin,
)
class UserManager(BaseUserManager):
"""Manager for users."""
def create_user(self, email, password=None, **extra_fields):
"""Create, save and return a new user."""
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
class User(AbstractBaseUser, PermissionsMixin):
"""User in the system."""
email = models.EmailField(max_length=255, unique=True)
name = models.CharField(max_length=255)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
# Asignar el UserManager a esta clase User
objects = UserManager()
USERNAME_FIELD = 'email'
```
Actualizar `settings.py` para que Django utilize este modelo de autenticación
agregando al final del archivo lo sgte.
```py
...
AUTH_USER_MODEL = 'core.User'
```
Crear migraciones
`docker compose run --rm app sh -c "python manage.py makemigrations"`
```sh
[+] Creating 1/0
✔ Container recipes_api_django-db-1 Running 0.0s
Migrations for 'core':
core/migrations/0001_initial.py
- Create model User
```
Codigo autogenerado [0001_initial.py](./app/core/migrations/0001_initial.py)
para app `core`
Aplicar migraciones
`docker compose run --rm app sh -c "python manage.py wait_for_db &&
python manage.py migrate"`
```sh
[+] Creating 1/0
✔ Container recipes_api_django-db-1 Running 0.0s
Waiting for database...
Database available!
Operations to perform:
Apply all migrations: admin, auth, contenttypes, core, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0001_initial... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying core.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying sessions.0001_initial... OK
```
En caso arrojar error por haber aplicado alguna migración previa se puede correr
`docker rm <db_volume>`, si *"esta en uso"* primero correr `docker compose down`.
Los nombres se pueden ver con `docker volume ls`
Al correr los tests nuevamente `docker compose run --rm app sh -c "python
manage.py test"`
```sh
[+] Creating 1/0
✔ Container recipes_api_django-db-1 Running 0.0s
Found 5 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
...Waiting for database...
Database unavailable, waiting 1 second...
Database unavailable, waiting 1 second...
Database unavailable, waiting 1 second...
Database unavailable, waiting 1 second...
Database unavailable, waiting 1 second...
Database available!
.Waiting for database...
Database available!
.
----------------------------------------------------------------------
Ran 5 tests in 0.675s
OK
Destroying test database for alias 'default'...
```
## Normalización de direcciones de email
### Test normalize email addresses
[test_models.py](./app/core/tests/test_models.py)
```py
def test_new_user_email_normalized(self):
"""Test email is normalized for new users."""
sample_emails = [
['test1@EXAMPLE.com', 'test1@example.com'],
['test2@Example.com', 'test2@example.com'],
['TEST3@EXAMPLE.COM', 'TEST3@example.com'],
['test4@example.COM', 'test4@example.com'],
]
for email, expected in sample_emails:
user = get_user_model().objects.create_user(email, 'sample123')
self.assertEqual(user.email, expected)
```
Modificar el `ceate_user` de [app/core/models.py](./app/core/models.py)
para utilizar el método `normalize_email` que provee la clase **BaseUserManager**
```diff
- user = self.model(email=email, **extra_fields)
+ user = self.model(email=self.normalize_email(email), **extra_fields)
```
## Requerir email
### Test requerir email
[test_models.py](./app/core/tests/test_models.py)
```py
def test_new_user_withouth_email_raises_error(self):
"""Test that creating a user withouth an email raises a ValueError."""
with self.assertRaises(ValueError):
get_user_model().objects.create_user('', 'test123')
```
Modificar el `ceate_user` de [app/core/models.py](./app/core/models.py)
y levantar excepción `ValueError` si usuario no ingresa un email
```py
def create_user(self, email, password=None, **extra_fields):
"""Create, save and return a new user."""
if not email:
raise ValueError('User must have an email address.')
user = self.model(email=self.normalize_email(email), **extra_fields)
user.set_password(password)
user.save(using=self._db)
```
## Funcionalidad super usuario
### Test creación de super usuario
[test_models.py](./app/core/tests/test_models.py)
```py
def test_create_superuser(self):
"""Test creating a superuser."""
user = get_user_model().objects.create_superuser(
'test@example.com',
'test123',
)
self.assertTrue(user.is_superuser)
self.assertTrue(user.is_staff)
```
Creación del método `create_superuser` para la clase `UserManager` en
[app/core/models.py](./app/core/models.py)
```py
def create_superuser(self, email, password):
"""Create and return a new superuser."""
user = self.create_user(email, password)
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
```
## Probando el modelo de usuario
Correr `docker compose up` y en otra terminal
`docker compose run --rm app sh -c "python manage.py createsuperuser"`
```sh
[+] Creating 1/0
✔ Container recipes_api_django-db-1 Running 0.0s
Email: admin@example.com
Password:
Password (again):
Superuser created successfully
```
## Django Admin
Es la interfáz gráfica para los modelos creados en el proyecto, permite
la administración basica C.R.U.D.
Requiere muy poco cóidgo para ser usado
![img](./imgs_readme/django_admin_00.png)
Se activa por modelo, en [`admin.py`](./app/core/admin.py)
### Personalización del administrador
Se crea una clase basada en `ModelAdmin` o `UserAdmin` donde se sobrescribe o
establecen variables de clase
ejemplo
```py
class UserAdmin(BaseUserAdmin):
"""Define de admin pages for users."""
ordering = ['id']
list_display = ['emial', 'name']
fieldsets = (
(None, {'fields': ('email', 'password')}),
)
readonly_files = ['last_login']
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': (
'email',
),
})
)
```
- `ordening` ![img](./imgs_readme/django_admin_01.png)
- `list_display` ![img](./imgs_readme/django_admin_02.png)
- `fieldsets` ![img](./imgs_readme/django_admin_03.png)
- `readonly_fields` ![img](./imgs_readme/django_admin_04.png)
- `add_fieldsets` ![img](./imgs_readme/django_admin_05.png)
### Creando test para el administrador
[`app/core/tests/test_models.py`](./app/core/tests/test_admin.py)
```py
class AdminSiteTests(TestCase):
"""Tests for Django admin."""
def setUp(self):
"""Create user and client."""
self.client = Client()
self.admin_user = get_user_model().objects.create_superuser(
email='admin@example.com',
password='testpass123',
)
self.client.force_login(self.admin_user)
self.user = get_user_model().objects.create_user(
email='user@example.com',
password='testpass123',
name='Test User'
)
def test_users_list(self):
"""Test that users are listed on page."""
url = reverse('admin:core_user_changelist')
res = self.client.get(url)
self.assertContains(res, self.user.name)
self.assertContains(res, self.user.email)
```
- Django docs
[reversing admin urls](https://docs.djangoproject.com/en/4.2/ref/contrib/admin/#reversing-admin-urls)
- Django docs
[testing tools](https://docs.djangoproject.com/en/4.2/topics/testing/tools/#overview-and-a-quick-example)
Correr test `docker compose run --rm app sh -c "python manage.py test"`
### Activar admin para core app
En [`admin.py`](./app/core/admin.py)
```py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from core import models
class UserAdmin(BaseUserAdmin):
"""Define the admin pages for users."""
ordering = ['id']
list_display = ['email', 'name']
admin.site.register(models.User, UserAdmin)
```
- **Admin**
![img](./imgs_readme/django_admin_06.png)
- **CORE** Section
![img](./imgs_readme/django_admin_07.png)
- **CORE** Usuarios, requiere modificar pues espera campos que el modelo no tiene
![img](./imgs_readme/django_admin_08.png)
### Modificar admin para que use los campos de usuario personalizado
```py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.utils.translation import gettext_lazy as _
from core import models
class UserAdmin(BaseUserAdmin):
"""Define the admin pages for users."""
ordering = ['id']
list_display = ['email', 'name']
filedsets = (
(None, {'fields': ('email', 'password')}),
(
_('Permissions'),
{
'fields': (
'is_active',
'is_staff',
'is_superuser',
)
}
),
(_('Important dates', {'fields': ('last_login',)})),
)
readonly_fields = ['last_login']
admin.site.register(models.User, UserAdmin)
```
- Administrador de usuario personalizado
![img](./imgs_readme/django_admin_09.png)
- Cambio de lenguaje y timezone, y traducción `gettext_lazy`
![img](./imgs_readme/django_admin_10.png)
- Requiere modificar pues espera campos que el modelo no tiene
- ![img](./imgs_readme/django_admin_11.png)
### Test página de creación de usuario
```py
def test_create_user_page(self):
"""Test the create user page works."""
url = reverse('admin:core_user_add')
res = self.client.get(url)
self.assertEqual(res.status_code, 200)
```
### Actualizar clase `UserAdmin` para que use los campos personalizados
[app/core/admin.py](./app/core/admin.py)
```py
class UserAdmin(BaseUserAdmin):
...
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': (
'email',
'password1',
'password2',
'name',
'is_active',
'is_staff',
'is_superuser',
)
}),
)
...
```
- Los test pasan
- Página para crear usuarios ![img](./imgs_readme/django_admin_12.png)
- Panel de usuarios del administrador ![img](./imgs_readme/django_admin_13.png)

View File

@ -107,9 +107,9 @@ AUTH_PASSWORD_VALIDATORS = [
# Internationalization # Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/ # https://docs.djangoproject.com/en/4.2/topics/i18n/
LANGUAGE_CODE = 'en-us' LANGUAGE_CODE = 'es-cl'
TIME_ZONE = 'UTC' TIME_ZONE = 'America/Santiago'
USE_I18N = True USE_I18N = True
@ -125,3 +125,5 @@ STATIC_URL = 'static/'
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field # https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
AUTH_USER_MODEL = 'core.User'

View File

@ -1,3 +1,46 @@
from django.contrib import admin # noqa """
Django admin customization.
"""
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.utils.translation import gettext_lazy as _
# Register your models here. from core import models
class UserAdmin(BaseUserAdmin):
"""Define the admin pages for users."""
ordering = ['id']
list_display = ['email', 'name']
fieldsets = (
(None, {'fields': ('email', 'password')}),
(
_('Permissions'),
{
'fields': (
'is_active',
'is_staff',
'is_superuser',
)
}
),
(_('Important dates'), {'fields': ('last_login',)}),
)
readonly_fields = ['last_login']
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': (
'email',
'password1',
'password2',
'name',
'is_active',
'is_staff',
'is_superuser',
)
}),
)
admin.site.register(models.User, UserAdmin)

View File

@ -0,0 +1,33 @@
# Generated by Django 4.2.5 on 2023-10-06 15:46
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('email', models.EmailField(max_length=255, unique=True)),
('name', models.CharField(max_length=255)),
('is_active', models.BooleanField(default=True)),
('is_staff', models.BooleanField(default=False)),
('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')),
('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')),
],
options={
'abstract': False,
},
),
]

View File

@ -1,3 +1,44 @@
from django.db import models # noqa """
Databse models.
"""
from django.db import models
from django.contrib.auth.models import (
AbstractBaseUser,
BaseUserManager,
PermissionsMixin,
)
# Create your models here.
class UserManager(BaseUserManager):
"""Manager for users."""
def create_user(self, email, password=None, **extra_fields):
"""Create, save and return a new user."""
if not email:
raise ValueError('User must have an email address.')
user = self.model(email=self.normalize_email(email), **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password):
"""Create and return a new superuser."""
user = self.create_user(email, password)
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
class User(AbstractBaseUser, PermissionsMixin):
"""User in the system."""
email = models.EmailField(max_length=255, unique=True)
name = models.CharField(max_length=255)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
# Asignar el UserManager a esta clase User
objects = UserManager()
USERNAME_FIELD = 'email'

View File

@ -0,0 +1,46 @@
"""
Tests for the Django admin modifications.
"""
from django.test import TestCase, Client
from django.contrib.auth import get_user_model
from django.urls import reverse
class AdminSiteTests(TestCase):
"""Tests for Django admin."""
def setUp(self):
"""Create user and client."""
self.client = Client()
self.admin_user = get_user_model().objects.create_superuser(
email='admin@example.com',
password='testpass123',
)
self.client.force_login(self.admin_user)
self.user = get_user_model().objects.create_user(
email='user@example.com',
password='testpass123',
name='Test User'
)
def test_users_list(self):
"""Test that users are listed on page."""
url = reverse('admin:core_user_changelist')
res = self.client.get(url)
self.assertContains(res, self.user.name)
self.assertContains(res, self.user.email)
def test_edit_user_page(self):
"""Test the edit user page works."""
url = reverse('admin:core_user_change', args=[self.user.id])
res = self.client.get(url)
self.assertEqual(res.status_code, 200)
def test_create_user_page(self):
"""Test the create user page works."""
url = reverse('admin:core_user_add')
res = self.client.get(url)
self.assertEqual(res.status_code, 200)

View File

@ -0,0 +1,46 @@
"""
Test for models.
"""
from django.test import TestCase
from django.contrib.auth import get_user, get_user_model
class ModelTests(TestCase):
"""Test models."""
def test_create_user_with_email_sucessfull(self):
"""Test creating a user with an email is sucessfull."""
email = 'test@example.com'
password = 'testpass123'
user = get_user_model().objects.create_user(
email=email,
password=password,
)
self.assertEqual(user.email, email)
self.assertTrue(user.check_password(password))
def test_new_user_email_normalized(self):
"""Test email is normalized for new users."""
sample_emails = [
['test1@EXAMPLE.com', 'test1@example.com'],
['test2@Example.com', 'test2@example.com'],
['TEST3@EXAMPLE.COM', 'TEST3@example.com'],
['test4@example.COM', 'test4@example.com'],
]
for email, expected in sample_emails:
user = get_user_model().objects.create_user(email, 'sample123')
self.assertEqual(user.email, expected)
def test_new_user_withouth_email_raises_error(self):
"""Test that creating a user withouth an email raises a ValueError."""
with self.assertRaises(ValueError):
get_user_model().objects.create_user('', 'test123')
def test_create_superuser(self):
"""Test creating a superuser."""
user = get_user_model().objects.create_superuser(
'test@example.com',
'test123',
)
self.assertTrue(user.is_superuser)
self.assertTrue(user.is_staff)

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 80 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 173 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 130 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 57 KiB