No module named base_user - Django - python

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'

Related

How do i add custom fields to UserManager in Django

I am trying to create a user profile, i followed through a tutorial which has registration for only username, email and password but i want to be able to add other custom fields.
What i did:
Models.py:
class UserManager(BaseUserManager):
def create_user(self, username, email, password=None,):
if username is None:
raise TypeError('User should have a userame')
if email is None:
raise TypeError('Users should have a Email')
user = self.model(username=username , email = self.normalize_email(email))
user.set_password(password)
user.save()
return user
def create_superuser(self, username, email, password=None):
if password is None:
raise TypeError('User should have a password')
user=self.create_user(username,email,password)
user.is_superuser = True
user.is_staff = True
user.save()
return user
class User(models.Model):
dso = models.ForeignKey(Dso,related_name='dso',default=NULL,blank=False,on_delete=models.CASCADE)
name = models.CharField(max_length=70, blank=False, default='')
email = models.EmailField(max_length=70, blank=False, default='')
password = models.CharField(max_length=70, blank=False, default='')
address = models.CharField(max_length=70, blank=False, default='')
roleId = models.IntegerField(blank=False, default='1')
isActive = models.BooleanField(blank=False, default=True)
customerId = models.CharField(max_length=70, blank=False, default='')
dateJoined = models.DateTimeField(auto_now_add=False, blank=False, default=NULL)
#property
def energy_data(self):
energydata = EnergyData.objects.filter(customerId=self.customerId).first()
return energydata
Serializers.py:
class RegisterSerializer(serializers.ModelSerializer):
password = serializers.CharField(max_length = 68, min_length=6, write_only = True)
class Meta:
model=User
fields=['email','username','password','name','address','customerId',
'dso', 'roleId']
def validate(self, attrs):
email = attrs.get('email', '')
username = attrs.get('username', '')
if not len(username) >= 4:
raise serializers.ValidationError('Username must be morethan 4 letters or characters')
return attrs
def create(self, validated_data):
return User.objects.create_user(**validated_data)
Views.py:
class RegisterView(generics.GenericAPIView):
serializer_class= RegisterSerializer
def post(self, request):
user = request.data
serializer = self.serializer_class(data=user)
serializer.is_valid(raise_exception=True)
serializer.save()
user_data = serializer.data
user= User.objects.get(email=user_data['email'])
token = RefreshToken.for_user(user).access_token
current_site = get_current_site(request).domain
relativeLink = reverse('email-verify')
absolute_url = 'http://'+current_site+relativeLink+"?token="+str(token)
email_body= 'Hi '+ user.username + ' Use this link below to verify your email \n'+ absolute_url
data = {'email_subject': 'Verify Your Email', 'email_body': email_body , 'to_email': user.email}
Util.send_email(data)
return Response(user_data, status = status.HTTP_201_CREATED)
URL Path:
path('register/', RegisterView.as_view(), name="register" )
When i do this and try to test i get the error, 'UserManager.create_user() got an unexpected keyword argument 'name''
Please kindly help as i am new to django rest frameworrk.
In your serializers.py you have the fields list that includes the variable 'name', but it is never defined in the models.py
Try to change serializers.py
fields=['email','username','password','address','customerId',
'dso', 'roleId']
And modify the variable name in models.py to be username instead of name
username = models.CharField(max_length=70, blank=False, default='')
Based on my experience with Django having a Model called "user" is going to create problems at some point since Django already have a User model pre-installed in the backend.
I know this is not the exact answer you were looking for, this will probably spare you a headache in the future.
To create a user profile I created the following model linking the User model with a OneToOneField.
class Profile(models.Model):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
bio = models.TextField()
profile_pic = models.ImageField(null=True, blank=True,upload_to="images/")
def __str__(self):
return str(self.user)
and obvioulsy imported
from django.contrib.auth.models import User
As a result,
I would remove your User model
Import "from django.contrib.auth.models import User"
add to the first line of your
UserManager Model, I would add
"user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)

Python migrations custom user model

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)

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/

Cannot input username into Custom super user Django

I want to create a custom authentication for Django. Created a custom class and manager as well. I'm not able to run the command python manage.py createsuperuser with --username attribute. It says there's not parameter like that.
Without username it gives a value error of null Username. Please help.
This is my models.py
from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import BaseUserManager
class AccountManager(BaseUserManager):
def create_user(self, email, password=None, **kwargs):
if not email:
raise ValueError('Users must have a valid email address')
if not kwargs.get('username'):
raise ValueError('Users must have a valid username')
account = self.model(
email=self.normalize_email(email), username=kwargs.get('username')
)
account.set_password(password)
account.save()
return account
def create_superuser(self, email, password, **kwargs):
account = self.create_user(email, password, **kwargs)
account.is_admin = True
account.save()
return account
class Account(AbstractBaseUser):
email = models.EmailField(unique=True)
username = models.CharField(max_length=40, unique=True)
first_name = models.CharField(max_length=40, blank=True)
last_name = models.CharField(max_length=40, blank=True)
tagline = models.CharField(max_length=150, blank=True)
is_admin = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = AccountManager()
USERNAME_FIELD = 'email'
REQUIRED_FILEDS = ['username']
def __unicode__(self):
return self.email
def get_full_name(self):
return ''.join([self.first_name, self.last_name])
def get_short_name(self):
return self.first_name

Categories

Resources