Python migrations custom user model - python

I was wondering if anyone could point me in the right direction, please? I have built a custom user model as per the below code, however, when I run 'make migrations' it doesn't seem to pick up a few of the fields I have added in the custom user model. I think this is the cause of the following error message whenever I try to create a superuser.
Traceback (most recent call last):
File "G:\Shares\Website\Development\Intranet\HealthcareProject4\manage.py", line 24, in <module>
execute_from_command_line(sys.argv)
File "G:\Shares\Website\Development\Intranet\HealthcareProject4\env\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "G:\Shares\Website\Development\Intranet\HealthcareProject4\env\lib\site-packages\django\core\management\__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "G:\Shares\Website\Development\Intranet\HealthcareProject4\env\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv
self.execute(*args, **cmd_options)
File "G:\Shares\Website\Development\Intranet\HealthcareProject4\env\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 59, in execute
return super().execute(*args, **options)
File "G:\Shares\Website\Development\Intranet\HealthcareProject4\env\lib\site-packages\django\core\management\base.py", line 353, in execute
output = self.handle(*args, **options)
File "G:\Shares\Website\Development\Intranet\HealthcareProject4\env\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 184, in handle
self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
File ".\HealthcareProject4\Users2\models.py", line 32, in create_superuser
return self._create_user(email, password, True, True, **extra_fields)
File ".\HealthcareProject4\Users2\models.py", line 23, in _create_user
date_joined=now, **extra_fields)
File "G:\Shares\Website\Development\Intranet\HealthcareProject4\env\lib\site-packages\django\db\models\base.py", line 485, in __init__
raise TypeError("'%s' is an invalid keyword argument for this function" % kwarg)
TypeError: 'is_staff' is an invalid keyword argument for this function
import datetime
from django.db import models
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser
)
from django.core.mail import send_mail
from django.utils.translation import ugettext_lazy as _
class CustomUserManager(BaseUserManager):
def _create_user(self, email, password, is_staff, is_superuser, **extra_fields):
"""
Creates and saves a User with the given email and password.
"""
now = datetime.datetime.now()
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
user = self.model(email=email,
is_staff=is_staff, is_active=True,
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, email, password=None, **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)
class CustomUser(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
username = models.CharField(max_length=150, unique=True)
first_name = models.CharField(max_length=150, blank=True)
surname = models.CharField(max_length=150, blank=True)
address1 = models.CharField(max_length=254, blank=True)
address2 = models.CharField(max_length=254, blank=True)
area_code = models.CharField(max_length=20, blank=True)
country_code = models.CharField(max_length=10, blank=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=True) # a admin user; non super-user
is_student = models.BooleanField(default=True)
is_admin = models.BooleanField(default=True) # a superuser
timestamp = models.DateTimeField(auto_now_add = True)
confirmed = models.BooleanField(default=False)
confirmed_date = models.DateTimeField(auto_now = True)
objects = CustomUserManager()
# notice the absence of a "Password field", that is built in.
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'address1', 'address2', 'area_code', 'country_code'] # Email & Password are required by default.
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
def get_absolute_url(self):
return 'users/%s' % urlquote(self.email)
def get_full_name(self):
# The user is identified by their email address
full_name = '%s %s' %(self.first_name, self.surname)
return full_name.strip()
def get_short_name(self):
# The user is identified by their email address
return self.first_name
def email_user(self, subject, message, from_email=None):
"""
Sends an email to this User.
"""
send_mail(subject, message, from_email, [self.email])
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 True
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?"
return self.is_staff
#property
def is_admin(self):
"Is the user a admin member?"
return self.is_admin
#property
def is_student(self):
"is the user a student?"
return self.student
# Generated by Django 2.1.11 on 2022-03-13 22:26
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='CustomUser',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('email', models.EmailField(max_length=255, unique=True, verbose_name='email address')),
('username', models.CharField(max_length=150, unique=True)),
('first_name', models.CharField(blank=True, max_length=150)),
('surname', models.CharField(blank=True, max_length=150)),
('address1', models.CharField(blank=True, max_length=254)),
('address2', models.CharField(blank=True, max_length=254)),
('area_code', models.CharField(blank=True, max_length=20)),
('country_code', models.CharField(blank=True, max_length=10)),
('is_active', models.BooleanField(default=True)),
('timestamp', models.DateTimeField(auto_now_add=True)),
('confirmed', models.BooleanField(default=False)),
('confirmed_date', models.DateTimeField(auto_now=True)),
],
options={
'verbose_name': 'user',
'verbose_name_plural': 'users',
},
),
]

Your model seems fine to me but in manager I see some issues with create methods
Here is what my manager looks like:
from django.contrib.auth.models import BaseUserManager
from django.utils.translation import ugettext_lazy as _
import logging
log = logging.getLogger(__name__)
class UserManager(BaseUserManager):
def create_user(self, email, password=None, **kwargs):
if not email:
raise ValueError(_(f'Please enter an email address'))
email = self.normalize_email(email)
user = self.model(email=email, **kwargs)
user.set_password(password)
user.save()
log.info(f'User created with email: {email}')
return user
def create_superuser(self, email, password=None, **kwargs):
kwargs.setdefault('is_staff', True)
kwargs.setdefault('is_superuser', True)
if kwargs.get('is_staff') is not True:
raise ValueError(f'Superuser must have staff permission')
if kwargs.get('is_superuser') is not True:
raise ValueError(f'Superuser must have superuser permission')
log.info(f'Superuser created with email: {email}')
return self.create_user(email, password, **kwargs)
Here goes My custom user model:
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, Group
from django.utils.translation import ugettext_lazy as _
from .managers import UserManager
class User(AbstractBaseUser, PermissionsMixin):
"""User model saves all the details of a user """
CUSTOMER = 'CUSTOMER'
VENDOR = 'VENDOR'
CMS = 'CMS'
IMS = 'IMS'
ROLES = ((CUSTOMER, 'CUSTOMER'), (VENDOR, 'VENDOR'), (CMS, 'CMS'), (IMS, 'IMS'))
GENDER = (('M', 'MALE'), ('F', 'FEMALE'), ('O', 'OTHER'))
email = models.EmailField(_('Email Address'), unique=True, db_index=True)
phone_number = models.CharField(_('Phone Number'), max_length=15)
first_name = models.CharField(_('First Name'), max_length=60, null=True, blank=True)
last_name = models.CharField(_('Last Name'), max_length=60, null=True, blank=True)
gender = models.CharField(
_('Gender'), max_length=10, choices=GENDER, null=True, blank=True)
profile_pic = models.ImageField(
_('Profile Image'), blank=True, null=True, upload_to='profile_imgs')
created = models.DateTimeField(_('Date Created'), auto_now_add=True)
updated = models.DateTimeField(_('Last Updated'), auto_now=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_vendor = models.BooleanField(default=False)
role = models.CharField(max_length=30, choices=ROLES, default=CUSTOMER)
otp = models.CharField(max_length=10, null=True, blank=True)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
class Meta:
ordering = ['id']
def __str__(self):
return f'{self.first_name} {self.last_name}'
def __repr__(self):
return f'<User({self.__str__()})>'
def has_perm(self, perm, obj=None):
return super().has_perm(perm, obj)
def has_module_perms(self, app_label):
return super().has_module_perms(app_label)

Related

TypeError when creating superiser in Django using custom users app

I am building a custom users app in Django for the web application I am making and tried to create a superuser (using this command: python manage.py createsuperuser), I added the username, email and phone number but when I enter the password (letters and numbers) I got the following error:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
main()
File "manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/home/john/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line
utility.execute()
File "/home/john/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 413, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/john/venv/lib/python3.6/site-packages/django/core/management/base.py", line 354, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/john/venv/lib/python3.6/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 79, in execute
return super().execute(*args, **options)
File "/home/john/venv/lib/python3.6/site-packages/django/core/management/base.py", line 398, in execute
output = self.handle(*args, **options)
File "/home/john/venv/lib/python3.6/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 "/home/john/users/models.py", line 47, in create_superuser
return self._create_user(username, phone_number, email, password, True, True, **extra_fields)
File "/home/john/users/models.py", line 29, in _create_user
user.set_password(password)
File "/home/john/venv/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 99, in set_password
self.password = make_password(raw_password)
File "/home/john/venv/lib/python3.6/site-packages/django/contrib/auth/hashers.py", line 79, in make_password
% type(password).__qualname__
TypeError: Password must be a string or bytes, got int.
this is the model.py script for the users model
import random
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.core import validators
from django.utils import timezone
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager, send_mail
class UserManager(BaseUserManager):
use_in_migrations = True
def _create_user(self, username, phone_number, email, password, is_staff, is_superuser, **extra_fields):
now = timezone.now()
if not username:
raise ValueError('The given username must be set')
email = self.normalize_email(email)
user = self.model(phone_number=phone_number,
username=Username, email=email,
is_staff=is_staff, is_active=True,
is_superuser=is_superuser,
date_joined=now, **extra_fields)
if not extra_fields.get('no_password'):
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, username=None, phone_number=None, email=None, password=None, **extra_fields):
if username is None:
if email:
username = email.split('#', 1)[0]
if phone_number:
username = random.choice('abcdefghijklmnopqrstuvwxyz') + str(phone_number)[-7:]
while User.objects.filter(username=username).exists():
username += str(random.randint(10, 99))
return self._create_user(username, phone_number, email, password, False, False, **extra_fields)
def create_superuser(self, username, phone_number, email, password, **extra_fields):
return self._create_user(username, phone_number, email, password, True, True, **extra_fields)
def get_by_phone_number(self, phone_number):
return self.get(**{'phone_number': phone_number})
class User(AbstractBaseUser, PermissionsMixin):
username = models.CharField(_('username'), max_length=32, unique=True,
help_text=
'Required. 30 characters or fewer starting with a letter. Letters, digits',
validators=[
validators.RegexValidator(r'^[a-zA-Z][a-zA-Z0-9_\.]+$',
_('Enter a valid username starting with a-z.'
'This value may contain only letters and numbers'
'and underscore characters.'), 'invalid')
],
error_messages={
'unique':_('A user with that username already exists.'),
}
)
first_name = models.CharField(_('first name'), max_length=30, blank=True)
last_name = models.CharField(_('last name'), max_length=30, blank=True)
email = models.EmailField(_('email address'), unique=True, null=True, blank=True)
phone_number = models.BigIntegerField(_('phone number'), unique=True, null=True, blank=True,
validators=[
validators.RegexValidator(r'^319[0-3,9]\d{8}$',
('Enter a valid mobile number.'), 'egrwfk')
],
error_messages={
'unique': _('A user with this mobile phone number already exits')
}
)
is_staff = models.BooleanField(_('staff status'), default=False,
help_text='designates whether this user can log into this admin site.')
is_active = models.BooleanField(_('active'), default=True,
help_text=_('designates whether this user should be treated as active'))
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
last_seen = models.DateTimeField(_('last seen date'), null=True)
objects = UserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELS = ['email', 'phone_number']
class Meta:
db_table = 'users'
verbose_name = _('user')
verbose_name_plural = _('users')
def get_full_name(self):
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
return self.first_name
def email_user(self, subject, message, from_email=None, **kwargs):
send_mail(subject, message, from_email, [self.email], **kwargs)
#property
def is_loggedin_user(self):
return self.phone_number is not None or self.email is not None
def save(self, *args, **kwargs):
if self.email is not None and self.email.strip() == '':
self.email = None
super().save(*args, **kwargs)
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
nick_name = models.CharField(_('nick_name'), max_length=150, blank=True)
avatar = models.ImageField(_('avatar'), blank=True)
birthday = models.DateField(_('birthday'), null=True, blank=True)
gender = models.NullBooleanField(_('gender'), help_text='femal is False, male is True, null is unset')
province = models.ForeignKey(verbose_name=_('province'), to='Province', null=True, on_delete=models.SET_NULL)
# email = models.EmailField(_('email_address'), blank=True)
# phone_number = models.BigIntegerField(_('phone_number'), null=True, blank=True,
# validators=[
# validators=RegexValidators(r'^989[0-3,9]\d(8)$,
# _('Enter a valid mobile number'), 'invalid'),
# ],
# )
class Meta:
db_table = 'user_profiles'
verbose_name = _('profile')
verbose_name_plural = _('profiles')
#property
def get_first_name(self):
return self.user.first_name
#property
def get_last_name(self):
return self.user.last_name
def get_nick_name(self):
return self.nick_name if self.nick_name else self.user.username
class Device(models.Model):
WEB = 1
IOS = 2
ANDROID = 3
DEVICE_TYPE_CHOICES = (
(WEB, 'web'),
(IOS, 'ios'),
(ANDROID, 'android')
)
user = models.ForeignKey(User, related_name='devices', on_delete=models.CASCADE)
device_uuid = models.UUIDField(_('Device UUID'), null=True)
# notify_token = models.CharField(_('notification token'), max_length=200, blank=True,
# validators=[validators.RegexValidator(r'([a-z]|[A-z]|[0-9])\w+',
# _('Notify token is not valid'), 'invalid')]
# )
last_login = models.DateTimeField(choices=DEVICE_TYPE_CHOICES, default=ANDROID)
device_type = models.PositiveSmallIntegerField(choices=DEVICE_TYPE_CHOICES, default=ANDROID)
device_os = models.CharField(_('device os'), max_length=20, blank=True)
device_model = models.CharField(_('device model'), max_length=50, blank=True)
app_version = models.CharField(_('app version'), max_length=20, blank=True)
created_time = models.DateTimeField(auto_now_add=True)
class Meta:
db_table = 'user_devices'
verbose_name = _('device')
verbose_name_plural = _('devices')
unique_together = ('user', 'device_uuid',)
class Province(models.Model):
name = models.CharField(max_length=50)
is_valid = models.BooleanField(default=True)
modified_at = models.DateTimeField(auto_now=True)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
I tried only string password but still getting the error. what could be the issue?
You've used REQUIRED_FIELS instead of REQUIRED_FIELDS in your User model.

Django attribute error while creating superuser

I've created a custom user model using AbstractBaseUser. When I try to create a super user using terminal via createsuperuser command.
I get
in create_superuser
user.is_staff = True
AttributeError: can't set attribute
Below is my code for creating custom user model.
import uuid
from django.db import models
from django.contrib.auth.models import (
AbstractBaseUser, AbstractUser, BaseUserManager
)
class AdminUserManager(BaseUserManager):
def create_user(self, email_id, password=None, *args, **kwargs):
if not email_id:
raise ValueError('User must have an Email ID')
user = self.model(email_id=email_id)
user.set_password(password)
user.save(using = self._db)
return user
def create_staffuser(self, email_id, password, *args, **kwargs):
user = self.create_user(
email_id, password=password
)
user.is_staff = True
user.save(using = self._db)
return user
def create_superuser(self, email_id, password, *args, **kwargs):
user = self.create_user(
email_id, password=password
)
user.is_staff = True
user.is_superuser = True
user.save(using = self._db)
return user
USER_ROLE = (
('pilot', 'pilot'),
('admin', 'admin')
)
class AdminUser(AbstractBaseUser):
user_uid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
profile_picture = models.ImageField(upload_to='user_profile_picture/', null=True, blank=True)
user_role = models.CharField(max_length=10, choices=USER_ROLE)
email_id = models.EmailField(verbose_name='Email ID', unique=True)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
phone_number = models.CharField(max_length=20)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
is_verified = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
USERNAME_FIELD = 'email_id'
REQUIRED_FIELDS = ['first_name', 'last_name']
def get_full_name(self):
full_name = f'{self.first_name} {self.last_name}'
return full_name
def get_short_name(self):
return self.first_name
def __str__(self):
return self.email_id
#property
def is_staff(self):
return self.is_staff
#property
def is_superuser(self):
return self.is_superuser
objects = AdminUserManager()

IntegrityError FOREIGN KEY constraint failed - Django custom user model

After creating a custom user model in Django and trying to edit a user in Django admin i get an IntegrityError.
I get a IntegrityError at /admin/accounts/customuser/add/ FOREIGN KEY constraint failed when I delete a user in Django admin. This also happens when I try to add a user in Django admin.
Code
models.py
from django.contrib.auth.models import AbstractUser, BaseUserManager
from django.db import models
from django.utils.translation import gettext_lazy as _
class UserManager(BaseUserManager):
def _create_user(self, email, password, **kwargs):
if not email:
raise ValueError("Email is required")
email = self.normalize_email(email)
user = self.model(email=email, **kwargs)
user.set_password(password)
user.save()
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, **kwargs):
kwargs.setdefault('is_staff', True)
kwargs.setdefault('is_superuser', True)
kwargs.setdefault('is_active', True)
if kwargs.get('is_staff') is not True:
raise ValueError("Superuser must have is_staff True")
if kwargs.get('is_superuser') is not True:
raise ValueError("Superuser must have is_superuser True")
return self._create_user(email, password, **kwargs)
class CustomUser(AbstractUser):
username = None
first_name = None
last_name = None
email = models.EmailField(_('email address'), blank=False, null=False, unique=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
full_name = models.CharField(_('full name'), max_length=1000, null=True, blank=True)
user_id = models.CharField(_('session id'), max_length=10000, null=True, blank=True)
verification_code_time = models.IntegerField(_('time left for session id'), null=True, blank=True)
verification_code = models.IntegerField(_('verification code'), null=True, blank=True)
objects = UserManager()
def __str__(self):
return self.email
admin.py
from django.contrib import admin
from .models import CustomUser
admin.site.register(CustomUser)
Any suggestions?

Django saving the registration extends AbstractBaseUser

Good day SO.
I am new to Django and having troubles with something basic. What I am trying to do is when I click on register, I want to create an Account and at the same time, a company account.
When I click on sumbit, the template returns my Account(the OneToOneField) This field is required.
Though my methods might be not aligned with good practice, but I hope that you can help me with this. I have been trying to check with other resources for two days but I can't seem to find the solution to my concern.
Here is my forms.py:
from django import forms
from django.contrib.auth.forms import UserCreationForm
from .models import Account, CompanyAccount
class AccountCreationForm(UserCreationForm):
email = forms.EmailField(max_length=60, help_text="Required")
class Meta:
model = Account
fields = ("email", "username", "password1", "password2", "account_type")
class CompanyAccountForm(forms.ModelForm):
class Meta:
model = CompanyAccount
fields = "__all__"
my models.py:
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
# Create your models here.
class MyAccountManager(BaseUserManager):
def create_user(self, email, username, account_type, password):
if not email:
raise ValueError("Users must have an Email Address")
if not username:
raise ValueError("Users must have an Username")
if not account_type:
raise ValueError("Users must have an Account Type")
user = self.model(
email=self.normalize_email(email),
username=username,
password=password,
account_type=account_type,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, username, account_type, password):
user = self.create_user(
email=self.normalize_email(email),
username=username,
password=password,
account_type=account_type,
)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
class Account(AbstractBaseUser):
email = models.EmailField(verbose_name='Email', max_length=60, default='', null=False, unique=True)
username = models.CharField(verbose_name='Username', max_length=50, default='', null=False, unique=True)
date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
last_joined = models.DateTimeField(verbose_name='last joined', auto_now_add=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
ACCOUNT_TYPE_CHOICES = (
(1, 'Applicant'),
(2, 'Company'),
(3, 'Client'),
)
account_type = models.PositiveSmallIntegerField(default=0, choices=ACCOUNT_TYPE_CHOICES)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'account_type', ]
objects = MyAccountManager()
def __str__(self):
return self.username
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return True
class CompanyAccount(models.Model):
account = models.OneToOneField(Account, on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True)
company_name = models.CharField(max_length=100, default='', null=False)
views.py
context = {}
if request.method == "POST":
rForm = AccountCreationForm(request.POST)
cForm = CompanyAccountForm(request.POST)
if rForm.is_valid() and cForm.is_valid():
rForm.save()
cForm.save()
else:
rForm = AccountCreationForm()
context['rForm'] = rForm
cForm = CompanyAccountForm()
context['cForm'] = cForm
return render(request, 'registration/company_registration_form.html', context)
If you want your model's field to be allowed to be empty when submitting forms, add blank=True:
account = models.OneToOneField(Account, on_delete=models.CASCADE, blank=True)
https://docs.djangoproject.com/en/3.1/ref/models/fields/

No module named base_user - Django

In one of my models files in my Django project, I am trying to import AbstractBaseUser, and BaseUserManager from django.contrib.auth.base_user. I checked my site packages, and there is definitely a base_user python file in Django's auth directory, but I am getting this error when trying to make migrations.
ImportError: No module named base_user
If I was using the wrong Django version, it wouldn't show up in my site packages Django directory correct ? Also in Pycharm, my IDE, its not underlining it red with any errors.
models.py
from django.conf import settings
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.contrib.auth.hashers import get_hasher
from django.contrib.auth.models import PermissionsMixin
from django.db import models
from django.utils import timezone
from django.utils.text import slugify
class AccountUserManager(BaseUserManager):
# username is not used here, but is needed for facebook login to work correctly
def create_user(self, email, password=None, username=None, is_active=True):
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
)
user.set_password(password)
user.last_login = timezone.now()
user.language_code = settings.LANGUAGE_CODE
user.is_active = is_active
user.save(using=self._db)
return user
def create_superuser(self, email, password):
user = self.create_user(email,
password=password,
)
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
class Account(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True, max_length=255, verbose_name='Email',
help_text='Used for login and password recovery. Is also an account\'s display name if no Name is specified.')
first_name = models.CharField(max_length=100, blank=True, null=True, verbose_name='First Name',
help_text='User\'s first name.')
last_name = models.CharField(max_length=100, blank=True, null=True, verbose_name='Last Name',
help_text='User\'s last name.')
date_joined = models.DateTimeField(auto_now_add=True, verbose_name='Date Joined')
is_active = models.BooleanField(default=True, null=False, db_index=True, verbose_name='Is Active',
help_text='Uncheck to prevent user from being allowed to login.')
is_staff = models.BooleanField(default=False, null=False, verbose_name='Is Staff',
help_text='Grants administrator privileges.')
activation_key = models.CharField(max_length=40, blank=True, null=True)
key_expires = models.DateTimeField(blank=True, null=True)
objects = AccountUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
def get_full_name(self):
full_name = ''
if self.first_name is not None:
full_name += self.first_name
if self.last_name is not None:
full_name += ' ' + self.last_name
return full_name
# #property
def _full_name(self):
return self.get_full_name()
_full_name.short_description = 'Name'
full_name = property(_full_name)
def get_display_name(self):
if self.full_name.strip():
return self.full_name.rstrip()
return self.email.rstrip()
#property
def slug(self):
if self.full_name:
return slugify(self.full_name)
email_parts = self.email.split('#')
return slugify(email_parts[0])
def __unicode__(self):
return unicode(self.email)
class Meta:
verbose_name = 'User Account'
verbose_name_plural = 'User Accounts'

Categories

Resources