Home > Software engineering >  How do i extend Django's auth user manager to add a method of my own?
How do i extend Django's auth user manager to add a method of my own?

Time:11-08

I'm using Python 3.9 and Django 3.2. I want to use Django's auth module for basic user management and have added this in my settings.py file

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'cbapp',
]

However, I woudl like to change the primary key of its user table to be a UUID and then add my own method, so I created this file at models/custom_user.py

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


class CustomeUserManager(models.Manager):
    def get_active_users(self):
        qset = CustomUser.objects.filter(
            is_active=True
        )
        return list(qset)
        

class CustomUser(AbstractUser):
    pass
    uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

    objects = CustomeUserManager()

I would still like to have access to Django's original auth methods though, but it seems like I can't access them anymore, for example "create_user" ...

>>> user = CustomUser.objects.create_user('Dave', '[email protected]', 'johnpassword')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    user = CustomUser.objects.create_user('Dave', '[email protected]', 'johnpassword')
AttributeError: 'CustomeUserManager' object has no attribute 'create_user'

What's the proper way to extend Django's auth user methods while adding some of my own?

CodePudding user response:

These are specified in the UserManager [Django-doc], you thus should inherit from the UserManager instead of a simple Manager:

from django.contrib.auth.models import UserManager

class CustomeUserManager(UserManager):
    def get_active_users(self):
        return CustomUser.objects.filter(
            is_active=True
        )

I would strongly advise not to return a list but a QuerySet for your get_active_users. A QuerySet can be filtered further and thus will not make a database query that then later should be post-processed at the Django/Python layer.

  • Related