How to create a custom user model in django?

Member

by sabryna , in category: Python , 2 years ago

How to create a custom user model in django?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by tavares.willms , a year ago

@sabryna To create a custom user model in Django, you first need to create a new model that extends the AbstractBaseUser class. This class provides all the basic fields and methods for a user model, such as the username and password fields, as well as methods for authenticating and managing users. Here is an example of a custom user model:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from django.contrib.auth.models import AbstractBaseUser
from django.db import models

class CustomUser(AbstractBaseUser):
  email = models.EmailField(unique=True)
  name = models.CharField(max_length=100)
  is_staff = models.BooleanField(default=False)
  is_active = models.BooleanField(default=True)

  USERNAME_FIELD = 'email'

  def __str__(self):
    return self.email


Once you have created your custom user model, you need to tell Django to use it instead of the default user model. This can be done by setting the AUTH_USER_MODEL setting in your Django project's settings file:

1
AUTH_USER_MODEL = 'myapp.CustomUser'


After setting this, you can use your custom user model like any other model in your Django project. You can create instances of it, query it, and use it in your views and other parts of your project.

by katharina , a year ago

@sabryna 

To create a custom user model in Django, follow these steps:

  1. Create a new Django app for your custom user model by running the following command in your terminal:


python manage.py startapp users

  1. Open the models.py file in your new app and create a new model class for your custom user model.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# users/models.py

from django.contrib.auth.models import AbstractBaseUser, BaseUserManager

class CustomUserManager(BaseUserManager):
    def create_user(self, email, password=None):
        if not email:
            raise ValueError('Users must have an email address')
        
        user = self.model(
            email=self.normalize_email(email)
        )
        
        user.set_password(password)
        user.save(using=self._db)
        return user
    
    def create_superuser(self, email, password):
        user = self.create_user(
            email=self.normalize_email(email),
            password=password
        )
        
        user.is_admin = True
        user.is_staff = True
        user.save(using=self._db)
        return user


class CustomUser(AbstractBaseUser):
    email = models.EmailField(verbose_name='email', unique=True)
    full_name = models.CharField(max_length=255, blank=True)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    is_staff = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []
    
    objects = CustomUserManager()
    
    def __str__(self):
        return self.email
    
    def has_perm(self, perm, obj=None):
        return True
    
    def has_module_perms(self, app_label):
        return True
    
    @property
    def is_superuser(self):
        return self.is_admin
    
    @property
    def is_staff(self):
        return self.is_admin


  1. In the above code, we created a custom user model class called CustomUser by inheriting from AbstractBaseUser. We also created a custom user manager class called CustomUserManager by inheriting from BaseUserManager.
  2. In CustomUserManager, we defined two methods to create a new user and a new superuser using the create_user and create_superuser functions.
  3. In CustomUser, we defined the fields of our custom user model, including the email field, full_name field, and boolean fields to indicate if the user is active, a staff member, or an admin. We also set the required fields and the user name field, which is email.
  4. We added the custom user manager to the objects attribute of our CustomUser model.
  5. Finally, we defined two functions to check for user permissions and properties has_perm() and has_module_perms().
  6. Once you have created your custom user model, you need to update your project’s settings.py file to use it by setting the AUTH_USER_MODEL attribute to point to your new custom user model.
1
2
3
# settings.py

AUTH_USER_MODEL = 'users.CustomUser'


  1. To create the tables in the database, run the following command:


python manage.py makemigrations


python manage.py migrate

  1. Congratulations! You can now use your custom user model in your Django project like you would with Django's built-in user model.