As I extend the User model of django

1

I want to create something like a study blog, but I want to create a user that has more attributes than the default django auth_user, I read that this class can be extended and I saw an example more or less like this:

from django.db import models
from django.contrib.auth.models import User

# Create your models here.

class Usuario(models.Model):
        usuario = models.OneToOneField(User)
        fecha_nacimiento = models.DateField()
        sexo = models.CharField(max_length = 10)

I do not know if I explain, and excuse my ignorance I started django 3 days ago, and this is my first project in this framework.

    
asked by Jonnathan Carrasco 26.01.2018 в 05:53
source

1 answer

0

There are three ways to extend the user model

The first is with a OneToOne (just as you are doing)

from django.db import models
from django.contrib.auth.models import User


class Alumni(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    cinta = models.CharField(max_length=100)
# Create your models here.

The second Form is using AbstractUser for example:

from django.db import models

# Create your models here.
from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    bio = models.TextField(max_length=500, blank=True)
    cinta = models.CharField(max_length=30, blank=True)
    fecha_ingreso = models.DateField(null=True, blank=True)

This adds more fields to the user model that brings by deafult django

Lastly, the way to redo the whole Django user model, for example:

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.contrib.auth.models import PermissionsMixin
# Create your models here.


class UserManager(BaseUserManager, models.Manager):
    def _create_user(self, email, password,
                     is_active, is_superuser, **extra_fields):
        if not email:
            raise ValueError('El email debe ser obligatorio')
        email = self.normalize_email(email)

        user = self.model(email=email,
                          is_active=is_active,
                          is_superuser=is_superuser, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email, password=None, **extra_fields):
        return self._create_user(
            email, password, False, False, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        return self._create_user(
            email, password, True, True, **extra_fields)


class User(AbstractBaseUser, PermissionsMixin, models.Model):
    # unique, no se van a repetir
    id = models.AutoField(primary_key=True, unique=True)
    nombre = models.CharField(max_length=40)
    apaterno = models.CharField(max_length=40)
    amaterno = models.CharField(max_length=40)
    numero_celular = models.CharField(unique=True, max_length=10, null=True)
    email = models.CharField(unique=True, max_length=50)
    genero = models.CharField(
        choices=(('M', 'Mujer'), ('H', 'Hombre')), max_length=16, blank=True)
    fecha_nacimiento = models.DateField(blank=True, null=True)
    # intermediario entre trans de cada modelo, object managaer de cada modelo
    objects = UserManager()

    is_active = models.BooleanField(default=False)
    is_staff = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'

    def get_short_name(self):
        return self.nombre

The last two forms need to be added in settings.py as:

AUTH_USER_MODEL="Name_of_the_app.Name_of_themodel"

I hope this information will serve you in the future;)

    
answered by 26.01.2018 в 18:09