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.
Related
I have create two models CustomUser inheriting AbstractUser and UserProfile, and there is OneToOne relation between them.
then i run the following command:-
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
When i run the command for createsuperuser, i got error as bellow:-(model are posted in the end..)
PS C:\Users\akcai\OneDrive\Desktop\deep_Stuffs\git_cloned\PollingApplication> python manage.py createsuperuser
Email: admin#gmail.com
Name: admin
Username: admin
Password:
Password (again):
The password is too similar to the username.
This password is too short. It must contain at least 8 characters.
This password is too common.
Bypass password validation and create user anyway? [y/N]: y
profile create too..
Traceback (most recent call last):
File "C:\Users\akcai\OneDrive\Desktop\deep_Stuffs\git_cloned\PollingApplication\manage.py", line 22, in <module>
main()
File "C:\Users\akcai\OneDrive\Desktop\deep_Stuffs\git_cloned\PollingApplication\manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\akcai\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
utility.execute()
File "C:\Users\akcai\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 413, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\akcai\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\akcai\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 79, in execute
return super().execute(*args, **options)
File "C:\Users\akcai\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 398, in execute
output = self.handle(*args, **options)
File "C:\Users\akcai\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 189, in handle
self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
File "C:\Users\akcai\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\models.py", line 163, in create_superuser
return self._create_user(username, email, password, **extra_fields)
File "C:\Users\akcai\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\models.py", line 146, in _create_user
user.save(using=self._db)
File "C:\Users\akcai\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\base_user.py", line 67, in save
super().save(*args, **kwargs)
File "C:\Users\akcai\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 726, in save
self.save_base(using=using, force_insert=force_insert,
File "C:\Users\akcai\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 774, in save_base
post_save.send(
File "C:\Users\akcai\AppData\Local\Programs\Python\Python39\lib\site-packages\django\dispatch\dispatcher.py", line 180, in send
return [
File "C:\Users\akcai\AppData\Local\Programs\Python\Python39\lib\site-packages\django\dispatch\dispatcher.py", line 181, in <listcomp>
(receiver, receiver(signal=self, sender=sender, **named))
File "C:\Users\akcai\OneDrive\Desktop\deep_Stuffs\git_cloned\PollingApplication\user\models.py", line 27, in CreateProfile
user = CustomUser.objects.get(username=instance)
File "C:\Users\akcai\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\akcai\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 435, in get
raise self.model.DoesNotExist(
user.models.DoesNotExist: CustomUser matching query does not exist.
PS C:\Users\akcai\OneDrive\Desktop\deep_Stuffs\git_cloned\PollingApplication>
models.py:-
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.db.models.signals import post_save
# Create your models here.
class CustomUser(AbstractUser):
email = models.EmailField(max_length=250, null=False, unique=True)
name = models.CharField(max_length=50, null=False)
username = models.CharField(max_length=50, null=False)
password = models.CharField(max_length=15, null=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['name', 'username']
class UserProfile(models.Model):
user = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
def get_all_polls(self):
from polls.models import PollQuestion
pass
def CreateProfile(sender, instance, **kwargs):
print("profile create too..")
user = CustomUser.objects.get(username=instance)
UserProfile.objects.create(user=user)
post_save.connect(CreateProfile, sender=CustomUser)
# following = models.ManyToManyField(CustomUser, symmetrical=False, null=True)
after this i tried to login to admin portal and get:- CustomUser matching query does not exist.
After this i checked the db is there any user exist or not:-
>>> from user.models import CustomUser
>>> u = CustomUser.objects.get(id=1)
>>> vars(u)
{'_state': <django.db.models.base.ModelState object at 0x000001C3C5B4CCA0>, 'id': 1, 'last_login': datetime.datetime(2021, 9, 21, 6, 43, 56, 565960, tzinfo=<UTC>), 'is_superuser': True, 'first_name': '', 'last_name': '', 'is_staff': True, 'is_active': True, 'date_joined': datetime.datetime(2021, 9, 21, 6, 28, 44, 123074, tzinfo=<UTC>), 'email': 'admin#gmail.com', 'name': 'admin', 'username': 'admin', 'password': 'pbkdf2_sha256$260000$SP9TyZ6VOMIFlRwvuvmDn4$7sak8fWf7QMTPfefoPMyQpLjYk3XpumRaJ5MMxq2lH4='}
>>>
I am unable to figure out on my own, what i am doing wrong, please help to get out of this rid.
Hope to here from you soon..
Thanks in advance...
user = CustomUser.objects.get(username=instance)
makes little sense.
You're trying to get an user by querying whether their username equals an instance (of CustomUser).
This will cause Django to stringify the CustomUser, so your query ends up something like (if SQL were Python)
if username == "<CustomUser: 3>":
which obviously will yield no rows.
In general, you should not need both a custom user model and a user profile model. Maybe rethink your database models so you only have your custom user model, and be sure to use the AUTH_USER_MODEL setting to wire it up.
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()
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.
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
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