Modify the Django user model


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

2 answers


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

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)

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

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.perfil.es_astronauta

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.


answered by 19.04.2016 в 14:59