Here is my models.py file
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import UserManager,AbstractBaseUser,PermissionsMixin
# Create your models here.
class CustomUserManager(UserManager):
def _create_user (self, email,password, **extra_fields):
if not email:
raise ValueError('Please provide a valid email')
email= self.normalize_email(email)
user= self.model(email=email, **extra_fields)
user.set_password(password)
user.save( using= self.db )
return user
def create_user(self,email=None,password=None, **extra_fields):
extra_fields.setdefault('is_staff' ,False)
extra_fields.setdefault('is_superuser', False)
return self._create_user(email,password, **extra_fields)
def create_superuser(self,email=None,password=None, **extra_fields):
extra_fields.setdefault('is_staff' ,True)
extra_fields.setdefault('is_superuser', True)
return self._create_user(email,password, **extra_fields)
class User(AbstractBaseUser,PermissionsMixin):
email = models.EmailField(blank=True,default='',unique=True)
name = models.CharField(max_length=255,blank=False,default='',unique=True)
is_active = models.BooleanField(default=True)
is_superuser = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
date_joined = models.DateTimeField(default=timezone.now)
last_login = models.DateTimeField(blank=True, null=True)
objects = CustomUserManager()
USERNAME_FIELD = 'name'
EMAIL_FIELD = 'email'
REQUIRED_FIELDS = []
class Meta:
verbose_name = 'User'
verbose_name_plural = 'Users'
def get_full_name (self):
return self.name
def get_short_name(self):
return self.name or self.email.split('@')[0]
I am trying to create a custom user model in django. I want the user to register using their username and email and password. Howerver when i try to create the superuser, it never asks for the email and then throws this error:
File "C:UsersUserDesktopmyprojtodo_appmodels.py", line 8, in _create_user
raise ValueError(‘Please provide a valid email’)
ValueError: Please provide a valid email
2
Answers
The command
createsuperuser
only prompt for REQUIRED_FIELDS Ref.Expanding on @vvxhid’s answer. The
createsuperuser
command uses theREQUIRED_FIELDS
attribute in the model to prompt for fields apart fromUSERNAME_FIELD
.Change that in your model to
REQUIRED_FIELDS = ['email']