Issue with createsuperuser when implementing custom user model - python

I am trying to implement my own custom user model in Django 1.6 but I am getting this error.
Traceback (most recent call last):
File "./manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Users/gabriel/.virtualenvs/hang_server/lib/python3.4/site-packages/django/core/management/__init__.py", line 399, in execute_from_command_line
utility.execute()
File "/Users/gabriel/.virtualenvs/hang_server/lib/python3.4/site-packages/django/core/management/__init__.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/gabriel/.virtualenvs/hang_server/lib/python3.4/site-packages/django/core/management/base.py", line 242, in run_from_argv
self.execute(*args, **options.__dict__)
File "/Users/gabriel/.virtualenvs/hang_server/lib/python3.4/site-packages/django/core/management/base.py", line 285, in execute
output = self.handle(*args, **options)
File "/Users/gabriel/.virtualenvs/hang_server/lib/python3.4/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 141, in handle
self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
TypeError: create_superuser() missing 1 required positional argument: 'email'
Here is my UserManager
class UserManager(BaseUserManager):
def _create_user(self, username, email, password, is_staff, is_superuser, **extra_fields):
now = timezone.now()
email = self.normalize_email(email)
user = self.model(username=username, email=email,
is_staff=is_staff, is_active=False,
is_superuser=is_superuser, last_login=now,
date_joined=now, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, username, email=None, password=None, **extra_fields):
return self._create_user(username, email, password, False, False,
**extra_fields)
def create_superuser(self, username, email, password, **extra_fields):
user=self._create_user(username, email, password, True, True,
**extra_fields)
user.is_active=True
user.save(using=self._db)
return user
It seems like this would be fairly straight forward but I can't seem to figure out why I am getting this error in the first place because I do have email specified in my create_superuser function. I have looked through several tutorials online and can't see how this is implemented differently. Can someone explain what I am doing wrong?

Looking at the code for the management commands, it only prompts for fields in the user model's REQUIRED_FIELDS attribute (as well as username). That attribute contains email by default in AbstractBaseUser, but if you have overridden it - or not inherited from that model in the first place (which you should be doing) - then email will not be prompted, and not passed to the create_superuser method.

class User(AbstractBaseUser, PermissionsMixin):
username = models.CharField('username', max_length=150, unique=True)
email = models.EmailField('email address', unique=True, max_length = 255)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']
For me above code simply solved problems.

Solution :
Check the spelling of your REQUIRED_FIELDS

Related

not able to createsuperuser in django

I am not able to createsuperuser, I am getting the following error
Django Version 3.1.1
Traceback (most recent call last):
File "/Users/napoleon/django-app/mysite/manage.py", line 22, in <module>
main()
File "/Users/napoleon/django-app/mysite/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/Users/napoleon/django-app/pfs-venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/Users/napoleon/django-app/pfs-venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/napoleon/django-app/pfs-venv/lib/python3.9/site-packages/django/core/management/base.py", line 330, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/napoleon/django-app/pfs-venv/lib/python3.9/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 79, in execute
return super().execute(*args, **options)
File "/Users/napoleon/django-app/pfs-venv/lib/python3.9/site-packages/django/core/management/base.py", line 371, in execute
output = self.handle(*args, **options)
File "/Users/napoleon/django-app/pfs-venv/lib/python3.9/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 189, in handle
self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
AttributeError: 'UserManager' object has no attribute 'create_superuser'
basically its throwing
AttributeError: 'UserManager' object has no attribute 'create_superuser'
I read this alsoSO-related question I don't get it exactly as conveyed there.
Custom User models mainapp/models.py
import uuid
from django.contrib.auth.models import AbstractUser, UserManager
from django.db import models
class CustomUserManager(UserManager):
def create_user(self, email,date_of_birth, username,password=None,):
if not email:
msg = 'Users must have an email address'
raise ValueError(msg)
if not username:
msg = 'This username is not valid'
raise ValueError(msg)
# if not date_of_birth:
# msg = 'Please Verify Your DOB'
# raise ValueError(msg)
# user = self.model( email=UserManager.normalize_email(email),
# username=username,date_of_birth=date_of_birth )
user = self.model( email=UserManager.normalize_email(email),
username=username )
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self,email,username,password,date_of_birth):
user = self.create_user(email,password=password,username=username,date_of_birth=date_of_birth)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
# Custom User Model
class User(AbstractUser):
id = models.BigAutoField(primary_key=True)
user_uuid = models.UUIDField(default=uuid.uuid1())
full_name = models.CharField(max_length=200,default='')
email = models.CharField(max_length=200,default='')
#form can have empty value blank=True, db can have empty value null=True
email_last_verified_on = models.DateTimeField(null=True)
Settings.py
# Swapping the user model
AUTH_USER_MODEL = 'mainapp.User'
Please clarify, what am I missing ...
You need to add the UserManager to the User mode:
class User(AbstractUser):
# …
objects = CustomUserManager()
Without specifying the manager, it will fallback to the UserManager [Django-doc], not the CustomUserManager.

django custom user model gives me lazy reference error

My code is as shown below:
models/user.py
from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import (
AbstractBaseUser, PermissionsMixin,BaseUserManager
)
class UserManager(BaseUserManager):
def _create_user(self, email, password, **extra_fields):
"""
Creates and saves a User with the given email,and password.
"""
if not email:
raise ValueError('The given email must be set')
try:
with transaction.atomic():
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
except:
raise
def create_user(self, email, 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, password, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
return self._create_user(email, password=password, **extra_fields)
class User(AbstractBaseUser, PermissionsMixin):
"""
An abstract base class implementing a fully featured User model with
admin-compliant permissions.
"""
email = models.EmailField(max_length=40, unique=True)
first_name = models.CharField(max_length=30, blank=True)
last_name = models.CharField(max_length=30, blank=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
date_joined = models.DateTimeField(default=timezone.now)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']
def save(self, *args, **kwargs):
super(User, self).save(*args, **kwargs)
return self
models/init.py
from user import User
settings.py
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'django.middleware.clickjacking.XFrameOptionsMiddleware'
]
AUTH_USER_MODEL = 'dashboard.User'
After this when I run python manage.py migrate, it gives me the following error:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 164, in handle
pre_migrate_apps = pre_migrate_state.apps
File "/usr/local/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/usr/local/lib/python2.7/site-packages/django/db/migrations/state.py", line 218, in apps
return StateApps(self.real_apps, self.models)
File "/usr/local/lib/python2.7/site-packages/django/db/migrations/state.py", line 295, in __init__
raise ValueError("\n".join(error.msg for error in errors))
ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'dashboard.user', but app 'dashboard' doesn't provide model 'user'.
The field authtoken.Token.user was declared with a lazy reference to 'dashboard.user', but app 'dashboard' doesn't provide model 'user'.
Is it because of improper jwt token configuration or user model?
Have you tried retrieving your User model with get_user_model?
from django.contrib.auth import get_user_model
User = get_user_model()

Django abstract user model not migrating

So I am working on implementing a custom user model, and to do so i followed tutorial 'this tutorial.
These are the models:
class UserManager(BaseUserManager):
"""Define a model manager for User model with no username field."""
use_in_migrations = True
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 given email must be set')
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, password=None, **extra_fields):
"""Create and save a regular User with the given email and password."""
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, 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)
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)
class User(AbstractUser):
"""User model."""
username = None
email = EmailField(_('email address'), unique=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = UserManager()
I am now trying to run python3 manage.py migrate and I get this error:
[wtreston] ~/gdrive/mysite2/ $ python3 manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, reviews, sessions, users
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
utility.execute()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 164, in handle
pre_migrate_apps = pre_migrate_state.apps
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/migrations/state.py", line 218, in apps
return StateApps(self.real_apps, self.models)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/migrations/state.py", line 295, in __init__
raise ValueError("\n".join(error.msg for error in errors))
ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'users.user', but app 'users' doesn't provide model 'user'.
The field reviews.Answer.student was declared with a lazy reference to 'users.user', but app 'users' doesn't provide model 'user'.
The field reviews.ReviewBlock.teacher was declared with a lazy reference to 'users.user', but app 'users' doesn't provide model 'user'.
The field users.Student.user was declared with a lazy reference to 'users.user', but app 'users' doesn't provide model 'user'.
The field users.Teacher.user was declared with a lazy reference to 'users.user', but app 'users' doesn't provide model 'user'.
In my settings.py I have this line AUTH_USER_MODEL = 'users.User'
. and when I reference the AUTH_USER_MODEL with ForeignKeys, I first have from mysite import settings and then have ForeignKey(settings.AUTH_USER_MODEL)
Any help would be helpful! Thanks
You have inherited AbstractUser for your custom user model and you are inheriting BaseUserManager for UserManager
modify your manager like below by inheriting UserManager:
class MyUserManager(UserManager):
def create_user(self, email, password=None, **kwargs):
# override this method
def create_superuser(self, email, password, **kwargs):
# override this method
clean up migrations and database first and then apply migration with this changes.

Django Integrity Error- Unique Constraint Failed

Trying to create a simple launch page for my website to collect email addresses. When the user goes to submit, it is providing the following error (traceback below)--Unique Constraint Failed---accounts.user.username. I figured maybe this has to do with the email address entered overlapping with username, but as you can see in my accounts model--the username is created from the email. (Note the entire User and User Profile models are not being utilized throughout my site yet, but just preparing for future usage). Any help is appreciated. Thanks
Traceback (most recent call last):
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\crstu\PycharmProjects\dealmazing\dealmazing\views.py", line 15, in newsletter_signup
instance.save()
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\auth\base_user.py", line 74, in save
super(AbstractBaseUser, self).save(*args, **kwargs)
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py", line 708, in save
force_update=force_update, update_fields=update_fields)
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py", line 736, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py", line 820, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py", line 859, in _do_insert
using=using, raw=raw)
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\manager.py", line 122, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 1039, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\compiler.py", line 1060, in execute_sql
cursor.execute(sql, params)
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\utils.py", line 95, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\six.py", line 685, in reraise
raise value.with_traceback(tb)
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 323, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: accounts_user.username
my Accounts app model below:
from django.contrib.auth.models import (
AbstractBaseUser,
BaseUserManager,
PermissionsMixin
)
from django.db import models
from django.utils import timezone
from django.conf import settings
from django.db.models.signals import post_save
import os
def avatar_upload_path(instance, filename):
return os.path.join('avatars', 'user_{0}', '{1}').format(
instance.user.id, filename)
class UserManager(BaseUserManager):
def create_user(self, email, username=None, password=None):
if not email:
raise ValueError("Users must have an email address")
if not username:
username = email.split('#')[0]
user = self.model(
email=self.normalize_email(email),
username=username,
)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, username, password):
user = self.create_user(
email,
username,
password,
)
user.is_staff = True
user.is_superuser = True
user.save()
return user
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True)
username = models.CharField(max_length=40, unique=True, default='')
date_joined = models.DateTimeField(default=timezone.now)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
def __str__(self):
return "#{}".format(self.username)
def get_short_name(self):
return self.username
def get_long_name(self):
return "#{} ({})".format(self.username, self.email)
class UserProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True, related_name='profile')
first_name = models.CharField(max_length=40, default='', blank=True)
last_name = models.CharField(max_length=40, default='', blank=True)
bio = models.TextField(blank=True, default='')
avatar = models.ImageField('Avatar picture',
upload_to=avatar_upload_path,
null=True,
blank=True)
def __str__(self):
return self.user.username
#property
def get_avatar_url(self):
if self.avatar:
return '/media/{}'.format(self.avatar)
return 'http://www.gravatar.com/avatar/{}?s=128&d=identicon'.format(
'94d093eda664addd6e450d7e9881bcad'
)
def create_profile(sender, **kwargs):
if kwargs['created']:
user_profile = UserProfile.objects.create(user=kwargs['instance'])
post_save.connect(create_profile, sender=User)
and here's the view for my actual newsletter that is collecting email address. note i'm just temporarily redirecting to google for now as a test:
from django.shortcuts import render, redirect
from newsletters.forms import NewsletterUserSignUpForm
from accounts.models import User
def newsletter_signup(request):
if request.method == "POST":
form = NewsletterUserSignUpForm(request.POST)
if form.is_valid():
instance = form.save(commit=False)
if User.objects.filter(email=instance.email).exists():
print("Sorry this email already exists")
else:
instance.save()
return redirect("http://www.google.com")
else:
form = NewsletterUserSignUpForm()
template = "newsletters/sign_up.html"
return render(request, template, {'form': form})
sign up html form looks like this:
<div class="col-lg-6 offset-lg-3">
<form method="POST">
{% csrf_token %}
<div class="form-group">
<div class="col-xs-6 col-xs-offset-3">
{{ form.email}}
<button class="btn btn-primary" type="submit">Sign Up!</button>
</div>
</div>
</form>
</div>
</div>
Your User model has a username field which requires unique=True which is the cause of your problem. Now you might be having a user having a username field as '' which is default. Since you already have one user with this username you can't have another user with this field. You should check that user already exists in the db or not also you have to enter some username with a user don't use default with unique=True its a really bad design and always fails.
since you are using username = email.split('#')[0] to get the username for the user. It is possible that two different email would give you same value for the username. For example example#abc.com and example#def.com. What you need to do is figure out some other algorithm to set the username or a good idea can be to user the email as username.
In your Accounts app model try this user.save(using=self._db) , this might help you

Django Error in models.py

I have a question, when you create class and synchronize database brand me the following error.
(DjangoAvanzado)Ricardos-MacBook-Pro:SistemaDiscusiones ricardoeduardosaucedo$ python manage.py syncdb --settings=SistemaDiscusiones.settings.local
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute_from_command_line(sys.argv)
File "/Users/ricardoeduardosaucedo/DjangoAvanzado/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/Users/ricardoeduardosaucedo/DjangoAvanzado/lib/python2.7/site-packages/django/core/management/__init__.py", line 312, in execute
django.setup()
File "/Users/ricardoeduardosaucedo/DjangoAvanzado/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/ricardoeduardosaucedo/DjangoAvanzado/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/Users/ricardoeduardosaucedo/DjangoAvanzado/lib/python2.7/site-packages/django/apps/config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/ricardoeduardosaucedo/Curso Django Avanzado/SistemaDiscusiones/apps/users/models.py", line 5
class UserManager(BaseUserManager):
^
IndentationError: unexpected indent
Tracebacks can look scary, but in this case, the message is quite clear if you start at the bottom and work up.
File "/Users/ricardoeduardosaucedo/Curso Django Avanzado/SistemaDiscusiones/apps/users/models.py", line 5
class UserManager(BaseUserManager):
^
IndentationError: unexpected indent
The error message is telling you you have an indentation error on line 5 of Avanzado/SistemaDiscusiones/apps/users/models.py.
Check you do not have any spaces at the beginning of that line, and that you are not using tabs. If you still can't fix the problem, edit your question and post the code from that file.
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
class UserManager(BaseUserManager):
def _create_user(self, username, email, password, is_staff, is_superuser,
**extra_fields):
if not email:
raise ValueError('El email debe de ser obligatorio')
email = self.normalize_email(email)
user = self.model(username=username, email=email, is_activate=True,
is_staff=is_staff, is_superuser=is_superuser, **extra_fields)
user.set_password(password)
user.save(using = self.db)
return user
def create_user(self, username, email, password=None,
**extra_fields):
return self._create_user(username, email, password, False, False, **extra_fields)
def create_superuser(self, username, email, password,
**extra_fields):
return self._create_user(username, email, password, True, True, **extra_fields)
class User(AbstractBaseUser, PermissionsMixin):
username = models.CharField(max_length=50, unique=True)
email = models.EmailField(max_length=50, unique=True)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
avatar = models.URLField()
objects = UserManager()
is_activate = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
USERNAME_FIELD = 'username'
REQUIRE_FIELDS = ['email']
def get_short_name(self):
return self.username

Categories