I've defined a custom user model:
class User(AbstractUser):
REQUIRED_FIELDS = []
USERNAME_FIELD = 'email'
email = models.EmailField(
_('email address'),
max_length=150,
unique=True,
help_text=_('Required. 150 characters or fewer. Must be a valid email address.'),
error_messages={
'unique':_("A user with that email address already exists."),
},
)
The point of it being to use an email address instead of username.
I've put this in settings:
# custom user model
AUTH_USER_MODEL = 'workoutcal.User'
The user model works, but there's one problem. I can't create superusers:
(workout) n155-p250:workout sahandzarrinkoub$ ./manage.py createsuperuser
Email address: sahandz#kth.se
Password:
Password (again):
Traceback (most recent call last):
File "./manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
utility.execute()
File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 59, in execute
return super().execute(*args, **options)
File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute
output = self.handle(*args, **options)
File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 179, in handle
self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
TypeError: create_superuser() missing 1 required positional argument: 'username'
Seems like the create_superuser method used has username as a required argument. I've read in the docs that I need to implement my own CustomUserManager. I've already done so here:
class CustomUserManager(BaseUserManager):
def _create_user(self, email, password, is_staff, is_superuser, **extra_fields):
now = timezone.now()
if not email:
raise ValueError('email must be set')
email = self.normalize_email(email)
user = User(email = email, is_staff=is_staff,
is_superuser=is_superuser, date_joined=now,
**extra_fields)
user.set_password(password)
user.save()
return user
def create_user(self, email, password, **extra_fields):
return self._create_user(email, password, False, False, **extra_fields)
def create_superuser(self, email, password, **extra_fields):
return self._create_user(email, password, True, True, **extra_fields)
It seems clear that my CustomUserManager isn't managing the User model. There seems to be no documentation telling me where to actually set the CustomUserManager as the actual manager for the User model. Could somebody tell me how to do that?
You also need to tell the new user to use the new manager:
class User(AbstractUser): # in your custom user
#...
objects = CustomUserManager()
#...
Django does the same thing in the source code at line 325
As for:
There seems to be no documentation telling me where to actually set the CustomUserManager as the actual manager for the User model.
Yes, there is actually a nice doc for that too, but explained in a more general way:
https://docs.djangoproject.com/en/2.0/topics/db/managers/
Related
I am trying to build a user authentication app using django JWT token, when i try to test my user authentication api and validate the password and password2 , it generate the following error:
TypeError: User() got unexpected keyword arguments: 'password2'
My serializers.py is as follows:
from rest_framework import serializers
from account.models import User
class UserRegistrationSerializers(serializers.ModelSerializer):
password2=serializers.CharField(style={'input_type':'password'}, write_only=True)
class Meta:
model = User
fields=['email','name','tc','password','password2']
extra_kwargs={
'password':{'write_only':True}
}
def validate(self, attrs):
password=attrs.get('password')
password2=attrs.get('password2')
if password != password2:
raise serializer.ValidationError("Password and Confirm Password Does not match")
return attrs
def validate_data(self, validate_data):
return User.objects.create_user(**validate_data)
and my views.py is as follows:
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework import status
from rest_framework.views import APIView
from account.serializers import UserRegistrationSerializers
# Create your views here.
class UserRegistrationView(APIView):
def post(self, request, format=None):
serializer= UserRegistrationSerializers(data=request.data)
if serializer.is_valid(raise_exception=True):
user= serializer.save()
return Response({'msg':'Registration Successful'}, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
my models.py file is as follows:
from django.db import models
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser
# Create your models here.
class UserManager(BaseUserManager):
def create_user(self, email, name, tc, password=None, password2=None):
"""
Creates and saves a User with the given email, date of
birth and password.
"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
name=name,
tc=tc,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, name, tc, password=None):
"""
Creates and saves a superuser with the given email, date of
birth and password.
"""
user = self.create_user(
email,
password=password,
name=name,
tc=tc,
)
user.is_admin = True
user.save(using=self._db)
return user
class User(AbstractBaseUser):
email = models.EmailField(
verbose_name='Email',
max_length=255,
unique=True,
)
#date_of_birth = models.DateField()
name= models.CharField(max_length=200)
tc=models.BooleanField()
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
created_at=models.DateTimeField(auto_now_add=True)
updated_at=models.DateTimeField(auto_now=True)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['name','tc']
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return self.is_admin
def has_module_perms(self, app_label):
"Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return True
#property
def is_staff(self):
"Is the user a member of staff?"
# Simplest possible answer: All admins are staff
return self.is_admin
The full traceback is as follows:
Traceback (most recent call last): File
"D:\jwt\lib\site-packages\django\core\handlers\exception.py", line 55,
in inner
response = get_response(request) File "D:\jwt\lib\site-packages\django\core\handlers\base.py", line 197, in
_get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\jwt\lib\site-packages\django\views\decorators\csrf.py", line 54,
in wrapped_view
return view_func(*args, **kwargs) File "D:\jwt\lib\site-packages\django\views\generic\base.py", line 103, in
view
return self.dispatch(request, *args, **kwargs) File "D:\jwt\lib\site-packages\rest_framework\views.py", line 509, in
dispatch
response = self.handle_exception(exc) File "D:\jwt\lib\site-packages\rest_framework\views.py", line 469, in
handle_exception
self.raise_uncaught_exception(exc) File "D:\jwt\lib\site-packages\rest_framework\views.py", line 480, in
raise_uncaught_exception
raise exc File "D:\jwt\lib\site-packages\rest_framework\views.py", line 506, in
dispatch
response = handler(request, *args, **kwargs) File "D:\djangoauthapi1\account\views.py", line 13, in post
user= serializer.save() File "D:\jwt\lib\site-packages\rest_framework\serializers.py", line 212, in
save
self.instance = self.create(validated_data) File "D:\jwt\lib\site-packages\rest_framework\serializers.py", line 981, in
create
raise TypeError(msg) TypeError: Got a TypeError when calling User.objects.create(). This may be because you have a writable field
on the serializer class that is not a valid argument to
User.objects.create(). You may need to make the field read-only, or
override the UserRegistrationSerializers.create() method to handle
this correctly. Original exception was: Traceback (most recent call
last): File
"D:\jwt\lib\site-packages\rest_framework\serializers.py", line 962, in
create
instance = ModelClass._default_manager.create(**validated_data) File "D:\jwt\lib\site-packages\django\db\models\manager.py", line 85,
in manager_method return getattr(self.get_queryset(), name)(*args,
**kwargs) File "D:\jwt\lib\site-packages\django\db\models\query.py", line 669, in create
obj = self.model(**kwargs) File "D:\jwt\lib\site-packages\django\db\models\base.py", line 565, in
init
raise TypeError( TypeError: User() got unexpected keyword arguments: 'password2'
i have figured out each line of code but i am unable to catch what is exactly the error, please needful help is required.
Because your serializer has password2 but User model does not have.
Just pop password2 into validated_data
from rest_framework import serializers
from account.models import User
class UserRegistrationSerializers(serializers.ModelSerializer):
password2=serializers.CharField(style={'input_type':'password'}, write_only=True)
class Meta:
model = User
fields=['email','name','tc','password','password2']
extra_kwargs={
'password':{'write_only':True}
}
def validate(self, attrs):
password=attrs.get('password')
password2=attrs.pop('password2')
if password != password2:
raise serializer.ValidationError("Password and Confirm Password Does not match")
return attrs
def create(self, validate_data):
return User.objects.create_user(**validate_data)
models
from django.contrib.auth.models import User
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, UserManager, PermissionsMixin
class User(AbstractBaseUser, PermissionsMixin):
username = models.CharField(max_length=255, unique=True)
objects = UserManager()
USERNAME_FIELD = 'username'
error:
(env) ➜ authorization python manage.py createsuperuser
Username: soubhagya
Password:
Password (again):
Traceback (most recent call last):
File "manage.py", line 22, in <module>
main()
File "/Users/soubhagyapradhan/Desktop/upwork/polyverse/polyverse_api/env/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute
output = self.handle(*args, **options)
File "/Users/soubhagyapradhan/Desktop/upwork/polyverse/polyverse_api/env/lib/python3.8/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 "/Users/soubhagyapradhan/Desktop/upwork/polyverse/polyverse_api/env/lib/python3.8/site-packages/django/contrib/auth/models.py", line 163, in create_superuser
return self._create_user(username, email, password, **extra_fields)
File "/Users/soubhagyapradhan/Desktop/upwork/polyverse/polyverse_api/env/lib/python3.8/site-packages/django/contrib/auth/models.py", line 144, in _create_user
user = self.model(username=username, email=email, **extra_fields)
File "/Users/soubhagyapradhan/Desktop/upwork/polyverse/polyverse_api/env/lib/python3.8/site-packages/django/db/models/base.py", line 503, in __init__
raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg))
TypeError: User() got an unexpected keyword argument 'email'
(env) ➜ autherization
I am trying to create a superuser inside Django shell
Getting above error.
Please take a look what can be the reason
I want to make an AbstractUser without a username field so I got this:
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.core.validators import RegexValidator
class CustomUser(AbstractUser):
email = models.EmailField(max_length=254, unique=True)
username = None
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
session_token = models.CharField(max_length=10, default=0)
#Newsletter/Shipment Info (not required)
newsletter = models.BooleanField(default=False)
first_name = models.CharField(max_length=35, blank=True, null=True)
last_name = models.CharField(max_length=35, blank=True, null=True)
adress = models.CharField(max_length=50, blank=True, null=True)
city = models.CharField(max_length=50, blank=True, null=True)
postal_code = models.CharField(max_length=6, blank=True, null=True)
phone = models.CharField(max_length=9, validators=[RegexValidator(r'^\d{9}$/')], blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
I got this migrated into the database and now I need to craete an admin user so I would be able to enter the admin panel. I typed email and both passwords into the comand prompt after python manage.py createsuperuser and I got this error:
Traceback (most recent call last):
File "C:\Users\mateu\Documents\meadow\backend\manage.py", line 22, in <module>
main()
File "C:\Users\mateu\Documents\meadow\backend\manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\mateu\Documents\meadow\env\lib\site-packages\django\core\management\__init__.py", line 425, in execute_from_command_line
utility.execute()
File "C:\Users\mateu\Documents\meadow\env\lib\site-packages\django\core\management\__init__.py", line 419, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\mateu\Documents\meadow\env\lib\site-packages\django\core\management\base.py", line 373, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\mateu\Documents\meadow\env\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 79, in execute
return super().execute(*args, **options)
File "C:\Users\mateu\Documents\meadow\env\lib\site-packages\django\core\management\base.py", line 417, in execute
output = self.handle(*args, **options)
File "C:\Users\mateu\Documents\meadow\env\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 195, in handle
self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
TypeError: create_superuser() missing 1 required positional argument: 'username'
I have no idea how to fix it. Any thoughts?
You have to inherit from AbstractBaseUser not from AbstractUser and add Manager Class to it
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(max_length=255, unique=True)
is_superuser = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
# Add other fields here
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
class UserManager(BaseUserManager):
def _create_user(self, email, password, **extra_fields):
user = self.model(email=self.normalize_email(email), **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password, **extra_fields):
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, **extra_fields)
Don't forget
python manage.py makemigrations
python manage.py migrate
I recommend you to take a look at the docs
I have just started learning Django and stuck my self in very strange condition.
I have created my own CustomUser instead of available in django.contrib.auth.models for authentication purpose.
I am getting some error or problems all together ,while running the program,i am trying to post all of them bellow.
I know all of them are occurred due to some silly mistake which i am unable to figure out on my own
1) When ever i am trying to run python manage.py make migrations i am getting error as bellow:-
You are trying to add a non-nullable field 'password' to customusers without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit, and let me add a default in models.py
Select an option:
2) When using python manage.py runserver is worked fine and run a emulated server on my local computer.
Now when i am trying to access admin/ it shows me the following error**:-**
Internal Server Error: /admin/
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such column: loginsignup_customusers.password
Second after filling the signup form :-
Internal Server Error: /signup/
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Admin\PycharmProjects\ecommerceproject\loginsignup\views.py", line 11, in signup_view
fm.save()
File "C:\Users\Admin\PycharmProjects\ecommerceproject\loginsignup\forms.py", line 42, in save
user = CustomUserManager.objects.create_user(
AttributeError: type object 'CustomUserManager' has no attribute 'objects'
[11/Jun/2021 11:35:58] "POST /signup/ HTTP/1.1" 500 67683
Bellow i am posting CustomUser and CustomUserManager class :-
CustomUser:-
class CustomUsers(AbstractBaseUser, PermissionsMixin):
username = models.CharField(max_length=40, unique=True)
email = models.EmailField()
password1 = models.CharField(max_length=10, null=False)
objects = CustomUserManager()
USERNAME_FIELD = 'username'
CustomUserManager:-
class CustomUserManager(BaseUserManager):
def create_user(self, username, email, password, **other_fields):
email = email.normalize_email(email)
user = self.model(email=email, username=username, **other_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, username, email, password, **other_fields):
other_fields.setdefault('is_staff', True)
other_fields.setdefault('is_superuser', True)
other_fields.setdefault('is_active', True)
You might have another migration file in the migration folder, which you should delete and then try to run makemigrations. See this
I have the need of create an user account in my application using just the email and password fields. Due to this, my custom user model in my models.py is:
I customize the UserManager to create user
from django.contrib.auth.models import 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("Users must have an email address")
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):
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)
And my User model is:
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.utils.translation import ugettext_lazy as _
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True, null=True,
help_text=_('Required. Letters, digits and ''#/./+/-/_ only.'),
validators=[RegexValidator(r'^[\w.#+-]+$', _('Enter a valid email address.'), 'invalid')
])
is_staff = models.BooleanField(
_('staff status'),
default=False,
help_text=_('Designates whether the user can log into this site.'),
)
is_active = models.BooleanField(
_('active'),
default=True,
help_text=_(
'Designates whether this user should be treated as active. '
'Unselect this instead of deleting accounts.'
),
)
objects = UserManager()
USERNAME_FIELD = "email"
class Meta:
db_table = 'auth_user'
verbose_name_plural = 'Usuarios en la plataforma'
def __str__(self):
return "#{}".format(self.email)
In my settings I've add:
AUTH_USER_MODEL = ‘my_app_name.User’
CREATE USERS - UserCreationForm pre-built class
To create an user, I am using of the UserCreationForm class pre-built in the django core.
In this class the username field is used such as denoted here
According to the above, in my forms.py I have:
from django.contrib.auth.forms import UserChangeForm, UserCreationForm
class CustomUserChangeForm(UserChangeForm):
class Meta(UserChangeForm.Meta):
model = get_user_model()
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = get_user_model()
class UserCreateForm(UserCreationForm):
class Meta:
fields = ("email", "password1", "password2",)
model = get_user_model()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["email"].label = "Email address"
When I try execute the python manage.py makemigrations , I get this traceback output error
bgarcial#elpug ‹ testing ●● › : ~/workspace/ihost_project
[1] % python manage.py makemigrations accounts
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/django/core/management/__init__.py", line 341, in execute
django.setup()
File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/django/__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/django/apps/registry.py", line 115, in populate
app_config.ready()
File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/django/contrib/admin/apps.py", line 23, in ready
self.module.autodiscover()
File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover
autodiscover_modules('admin', register_to=site)
File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/django/utils/module_loading.py", line 50, in autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "/home/bgarcial/workspace/ihost_project/accounts/admin.py", line 8, in <module>
from .forms import CustomUserChangeForm, CustomUserCreationForm
File "/home/bgarcial/workspace/ihost_project/accounts/forms.py", line 16, in <module>
class CustomUserCreationForm(UserCreationForm):
File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/django/forms/models.py", line 257, in __new__
raise FieldError(message)
django.core.exceptions.FieldError: Unknown field(s) (username) specified for User
(ihost)
bgarcial#elpug ‹ testing ●● › : ~/workspace/ihost_project
Of course, I am using UserCreationForm django class core, I am forcing to use the django core functionalities in which the username field is required
How to can I remove the username or modify this?
I know the modify the django core is not recommended, but, how to can I create an user without include the username field making use of UserCreationForm django class core?
I try override the save method of my form in where I create the users, but I don't have clear the process, I think that the core of my inconvenient is in the use of UserCreationForm django class core ..
class UserCreateForm(UserCreationForm):
class Meta:
fields = ("email", "password1", "password2",)
model = get_user_model()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["email"].label = "Email address"
def save(self, commit=True):
user = super(UserCreateForm, self).save(commit=False)
user.email = self.cleaned_data["email"]
# Tell to Django that not check the username
if commit:
user.save()
return user
If somebody can point me in the right direction will be very much appreciated. :)
I've found a solution that works.
anyways, feel free to suggest better solutions!
Like my inconvenient/error was related with the use of the UserCreationForm class pre-built in the django core which use the username field in their logic, then I proceeded to make the following:
In my forms.py in my class CustomUserCreationForm is a child of the class UserCreationForm, I've override/add to Meta class the attribute fields, using the email field instead of username field.
This question post help me with it.
My class CustomUserCreationForm stay as follow:
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = get_user_model()
fields = ('email',)
Then, I proceeded to perform my migrations:
[1] % python manage.py makemigrations accounts
SystemCheckError: System check identified some issues:
ERRORS:
<class 'accounts.admin.UserAdmin'>: (admin.E033) The value of 'ordering[0]' refers to 'username', which is not an attribute of 'accounts.User'.
This error showed me that the username field is not an attribute of my User model.
This means that Django follows trying to ask the username field, even though I overwritten the fields value with the email field.
Of course this is logic because I am still inherit from UserCreationForm class pre-built in the django core
Then, I've add the username field to my User model with null=True attribute, and of this way, the username does not required in the user account creation:
class User(AbstractBaseUser, PermissionsMixin):
# I had add the username field despite that I don't use in my User model
username = models.CharField(_('username'), max_length=30, null=True,
help_text=_('Required. 30 characters or fewer. Letters, digits and ''#/./+/-/_ only.'),
validators=[RegexValidator(r'^[\w.#+-]+$', _('Enter a valid username.'), 'invalid')
])
email = models.EmailField(unique=True, null=True,
help_text=_('Required. Letters, digits and ''#/./+/-/_ only.'),
validators=[RegexValidator(r'^[\w.#+-]+$', _('Enter a valid email address.'), 'invalid')
])
...
Of this way, I execute my migrations
bgarcial#elpug ‹ testing ●● › : ~/workspace/ihost_project
[1] % python manage.py makemigrations accounts
Migrations for 'accounts':
accounts/migrations/0001_initial.py:
- Create model User
(ihost)
bgarcial#elpug ‹ testing ●● › : ~/workspace/ihost_project
python manage.py migrate accounts ...
And my username field still persist in my custom user schema, just that is not required and when I created an user from my UserCreateForm class which inherit from UserCreationForm, I can create an user account with just email and password
I don`t know if this is the best approach to address this inconvenient.
Feel free to suggest improvements!