Modify the Django user model

4

Django has its own model for managing users for login, I would like to know if this can be modified.

The idea is to add some fields such as user type, mail, dependency, city, etc.

    
asked by Didier 19.04.2016 в 14:25
source

2 answers

3

friend you can extend it, I create something similar adding more fields.

models.py

from django.contrib.auth.models import AbstractUser
class Usuario(AbstractUser):
    telefono = models.CharField('Télefono', max_length=15)
    avatar = models.ImageField('avatar para tu perfil', upload_to='avatars/', blank=True, null=True)
    fondo = models.ImageField('Elige tu fondo de perfil', upload_to='fondos/', blank=True, null=True)

settings.py

# modelo que sirvio para extender campos a user
AUTH_USER_MODEL = 'usuarios.Usuario'
    
answered by 25.04.2016 / 20:08
source
3

To save information related to your users, it is possible to use a profile type model.

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

class Perfil(models.Model):
    usuario = models.OneToOneField(User, on_delete=models.CASCADE)
    es_astronauta = models.BooleanField(default=False)

Then, it is possible to access the user's profile as if you were accessing any other related model:

>>> usuario = User.objects.get(username='admin')
>>> usuario.pk
1
>>> usuario.perfil.es_astronauta
False

This is the simplest way. If you would like to have your own user model, you must inherit from AbstractBaseUser that contains all the implementation of the model although there are some design considerations that you have to take into account. You also have to implement your own Manager .

If you do not want to touch the user's original behavior, what you can do is also inherit from AbstractUser and add the necessary fields although Django himself recommends that you use a separate model like the one I showed you in the first part.

References

answered by 19.04.2016 в 14:59