Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

**extra_fields argument in Django

Tags:

python

django

I'm trying to create a custom user model in Django using this article

And there a model manager given in this article as :

from django.contrib.auth.base_user import BaseUserManager
from django.utils.translation import ugettext_lazy as _


class CustomUserManager(BaseUserManager):
    """
    Custom user model manager where email is the unique identifiers
    for authentication instead of usernames.
    """
    def create_user(self, email, password, **extra_fields):
        """
        Create and save a User with the given email and password.
        """
        if not email:
            raise ValueError(_('The Email must be set'))
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save()
        return user

    def create_superuser(self, email, password, **extra_fields):
        """
        Create and save a SuperUser with the given email and password.
        """
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('is_active', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError(_('Superuser must have is_staff=True.'))
        if extra_fields.get('is_superuser') is not True:
            raise ValueError(_('Superuser must have is_superuser=True.'))
        return self.create_user(email, password, **extra_fields)

What I dont understand is **extra_fields passed as argument in the create_user and create_superuser function.

What is **extra_fileds ??What is the purpose of it and what it is doing here??

Thanks in advance!!


1 Answers

**extra_fields is used so that any number of keywords argument (kwarg) can be passed to both the functions create_user and create_superuser.So if the arguments passed to the create_user and create_superuser are there in the associated Custom user model then a user model will be created with all that information.

It is also used to access the built-in fields of the default user model such as is_superuser,is_staff and is_active and assigned them a default value

like image 105
Prateek Gupta Avatar answered Oct 29 '25 11:10

Prateek Gupta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!