Update a model field fetching data from user model in django - django

I have a User model using AbstractBaseUser. I have a model Employee using Model class. I want that when a user is created though sign up, the user inherits all the fields of Employee model. I have made a OnetoOne relation between User model and Employee. But after creating an user when I query employee model, I can not find any data related to the created User.
User manager:
class UserManager(BaseUserManager):
"""
Creates and saves a User with the given email and password.
"""
def create_user(self, email, username, password=None):
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
username=username
)
user.set_password(password)
user.save(using=self._db)
return user
def create_staffuser(self, email,username, password):
user = self.create_user(
email,
password=password,
username=username
)
user.is_staff = True
user.save(using=self._db)
return user
def create_superuser(self, email, username, password):
user = self.create_user(
email,
password=password,
username=username
)
user.is_staff = True
user.is_admin = True
user.save(using=self._db)
return user
User:
class User(AbstractBaseUser):
"""
Creates a customized database table for user
"""
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
username = models.CharField(max_length=255, unique=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email',]
objects = UserManager()
def get_full_name(self):
# The user is identified by their email address
return self.email
def get_short_name(self):
# The user is identified by their email address
return 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
I have extended the user model with a OnetoOne relation using OneToOneField(User, on_delete=models.CASCADE, null=True)
Employee model:
class Employee(models.Model):
"""
Create employee attributes
"""
employee_user = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
e_id = models.IntegerField(unique=True, null=False)
first_name = models.CharField(max_length=128)
last_name = models.CharField(max_length=128)
address = models.CharField(max_length=256, blank=True)
phone_number = models.CharField(max_length=128, blank=True)
email = models.EmailField(max_length=128, unique=True)
def get_absolute_url(self):
return reverse("employee:employee-list")
#receiver(post_save, sender=User)
def create_or_update_user_profile(sender, instance, created, **kwargs):
if created:
Employee.objects.create(employee_user=instance)
instance.Employee.save()
In this model there is also a field named email. I have to keep this field because I am using this model to create a form for Employee creation. But the problem is, User model's email field is conflicting with employee email field. I have to keep both the email fields.
Can I update the employee email field with user email field?? If yes, then what should be the query???

you have created a custom user model soo you need to import he Auth_User_model from you setting file and than use that not the django inbuilt auth User.
You can do this
from django.conf import settings
employee_user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

Related

Getting error in Django Custom user model treating every created user as staff user why?

This is my code for Custom user model in Django app i want to make a ecommerce app but when i am creating a superuser in terminal and using that for login insted of making a super user the admin console is treating every account as staff account and even correct email and password is not working? can any one help
from django.db import models
from django.contrib.auth.models import AbstractBaseUser,BaseUserManager
# Create your models here
class MyAccountManager(BaseUserManager):
def create_user(self,first_name,last_name,username,email,password=None):
if not email:
raise ValueError('User must have an email address')
if not username:
raise ValueError('User must have an username')
user = self.model(
email=self.normalize_email(email),
username = username,
first_name = first_name,
last_name = last_name,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self,first_name,last_name,email,username,password):
user = self.create_user(
email=self.normalize_email(email),
username = username,
first_name = first_name,
last_name = last_name,
)
user.is_admin = True
user.is_active = True
user.is_staff = True
user.is_superadmin = True
user.save(using=self._db)
return user
class Account(AbstractBaseUser):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
username = models.CharField(max_length=50,unique=True)
email = models.EmailField(max_length=100, unique=True)
phone_number = models.CharField(max_length=50)
#required
date_joined = models.DateTimeField(auto_now_add=True)
last_login = models.DateTimeField(auto_now_add=True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
is_superadmin = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username','first_name','last_name']
objects = MyAccountManager()
def __str__(self):
return self.email
def has_perm(self, perm,obj=None):
return self.is_admin
def has_module_perms(self, add_label):
return True`
I want to make a custom user model

How to create multiple types of users using OneToOne field in Django?

I want to create 2 types of users - Customer and Company. I've already created a custom user shown below. These are their model files -
class UserManager(BaseUserManager):
"""Define a model manager for User model with no username field."""
class Types(models.TextChoices):
CUSTOMER = "CUSTOMER", "Customer"
COMPANY = "COMPANY", "Customer"
type = models.CharField(_("Type"), max_length=50, choices=Types.choices, default=Types.CUSTOMER)
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, is_staff=False, is_superuser=False, **extra_fields):
"""Create and save a regular User with the given email and password."""
extra_fields.setdefault('is_staff', is_staff)
extra_fields.setdefault('is_superuser', is_superuser)
return self._create_user(email, password, **extra_fields)
class User(AbstractUser):
"""User model."""
username=None
contact = models.CharField(max_length=100)
USERNAME_FIELD = 'id'
REQUIRED_FIELDS = ['password']
objects = UserManager()
class Customer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
name = models.CharField(max_length=100)
email = models.EmailField(_('email address')
class Company(models.Model):
"""User model."""
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
company_name = models.CharField(max_length=100)
company_email = models.EmailField(_('email address'), unique=True)
I'm stuck at creating the serializer file. Most of the other answers use forms for creating multiple types of users, but I just want to create an API. Can anyone help me to create the serializer file for this?
class UserListSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields="__all__"
class CustomerSerializer(serializers.ModelSerializer):
user = UserSerializer(many=True, read_only=True)
class Meta:
model = Customer
fields="__all__"
def create(self, validated_data):
????

Django Custom User Admin Panel won't log in

I just started a new Django project and I wanted to create my own customer user model instead of using the default. I pretty much followed the one in the documentation for 2.1 (my version of Django) except I added more fields and date_of_birth is called 'dob' and isn't required. But then when I create the superuser account, I can't log into the admin panel. It says, "Please enter the correct email address and password for a staff account. Note that both fields may be case-sensitive."
Here is my code:
users/models.py
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.utils.translation import gettext_lazy as _
# Create your models here.
class UserManager(BaseUserManager):
# python manage.py createuser
def create_user(self, email: str, password: str=None) -> 'User':
if not email:
raise ValueError('Users must have a valid email address.')
user = self.model(
email=self.normalize_email(email),
)
user.set_password(password)
user.save(using=self._db)
return user
# python manage.py createsuperuser
def create_superuser(self, email, password) -> 'User':
user = self.create_user(
email=email,
password=password,
)
user.is_admin = True
user.save(using=self._db)
return user
class User(AbstractBaseUser):
email = models.EmailField(
_('email address'), help_text=_('An email address'), max_length=127, unique=True, null=False, blank=False
)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
first_name = models.CharField(_('first name'), help_text=_('The user\'s given name'), blank=False, max_length=32)
last_name = models.CharField(
_('last name'), help_text=_('The user\'s surname or family name'), blank=False, max_length=32
)
dob = models.DateField(_('date of birth'), help_text=_('User\'s date of birth'), blank=False, null=True)
hometown = models.CharField(_('hometown'), help_text=_('Hometown'), blank=True, max_length=64)
country = models.CharField(_('country'), help_text=_('Country'), blank=True, max_length=64)
objects = UserManager()
USERNAME_FIELD = "email"
REQUIRED_FIELDS = []
def __str__(self):
return self.email
def get_full_name(self):
return self.first_name + " " + self.last_name
def get_short_name(self):
return self.first_name
def has_perm(self, perm, obj=None):
return self.is_staff
def has_module_perms(self, app_label):
return self.is_staff
#property
def is_staff(self) -> bool:
"""
Is the user a member of staff?
:return: If the user is an admin, then True. Else False
"""
return self.is_admin
I also changed my settings.py file to read:
AUTH_USER_MODEL = 'users.User'
and I made sure the app ('myproject.users.apps.UsersConfig') is added to the INSTALLED_APPS list. Note: my apps are all located one folder in, unlike the tutorial default. Ie:
myproject/
|-----> users/
|----->models.py
I think you missed one thing in User model,
Change is_active = models.BooleanField(default=False) to is_active = models.BooleanField(default=True)
Hence your model be like,
class User(AbstractBaseUser):
is_active = models.BooleanField(default=True)
# other fields
From the official doc,
is_active
Boolean. Designates whether this user account should be considered
active. We recommend that you set this flag to False instead of
deleting accounts; that way, if your applications have any foreign
keys to users, the foreign keys won’t break.

Use custom model from legacy database to authenticate login django

Probably a very basic question.
How can i use my own legacy db table for authenticating login of the users in Django?
All the methods i am finding seem really confusing.
I want to use Django's own authentication system with modification of 'Persons' database table instead of 'User'.
This is an example of implementing custom authentication:
person/models.py:
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.db import models
class PersonManager(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.')
person = self.model(
email=self.normalize_email(email), username=kwargs.get('username')
)
person.set_password(password)
person.save()
return person
def create_superuser(self, email, password, **kwargs):
person = self.create_user(email, password, **kwargs)
person.is_superuser = True
person.save()
return person
class Person(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)
# You may need to add more fields
is_superuser = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = PersonManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
def __str__(self):
return self.email
def get_full_name(self):
return '{} {}'.format(self.first_name, self.last_name)
def get_short_name(self):
return self.first_name
You will need to add AUTH_USER_MODEL = 'person.Person' to your settings.py file (I suppose that your app name is person). Now, your authentification system will use Person model instead of the default User model.
For more details, check this tutorial Extending Django's built-in User model

Django: Making the CustomUser appear in admin under Auth

How to make my CustomUser appear in admin under auth app like built-in user? I know there was a question like that here and I followed the solution people suggested, but what their solution do, is that it makes a Customer User in my app, not in an auth app, so like any other model that I create.
Here are my models:
class CustomUserManager(BaseUserManager):
def create_user(self, email, first_name, last_name, password=None,
**extra_fields):
'''
Create a CustomUser with email, name, password and other extra fields
'''
now = timezone.now()
if not email:
raise ValueError('The email is required to create this user')
email = CustomUserManager.normalize_email(email)
cuser = self.model(email=email, first_name=first_name,
last_name=last_name, is_staff=False,
is_active=True, is_superuser=False,
date_joined=now, last_login=now,)
cuser.set_password(password)
cuser.save(using=self._db)
return cuser
def create_superuser(self, email, first_name, last_name, password=None,
**extra_fields):
u = self.create_user(email, first_name, last_name, password,
**extra_fields)
u.is_staff = True
u.is_active = True
u.is_superuser = True
u.save(using=self._db)
return u
class CustomUser(AbstractBaseUser, PermissionsMixin):
'''
Class implementing a custom user model. Includes basic django admin
permissions and can be used as a skeleton for other models.
Email is the unique identifier. Email, password and name are required
'''
email = models.EmailField(_('email'), max_length=254, unique=True,
validators=[validators.validate_email])
username = models.CharField(_('username'), max_length=30, blank=True)
first_name = models.CharField(_('first name'), max_length=45)
last_name = models.CharField(_('last name'), max_length=45)
is_staff = models.BooleanField(_('staff status'), default=False,
help_text=_('Determines if user can access the admin site'))
is_active = models.BooleanField(_('active'), default=True)
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
objects = CustomUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']
def get_full_name(self):
'''
Returns the user's full name. This is the first name + last name
'''
full_name = "%s %s" % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
'''
Returns a short name for the user. This will just be the first name
'''
return self.first_name.strip()
And I also want to add ManyToManyField to 2 other models I have and make them appear in the user form in admin.
Does it mean that I have to write my own form? Or maybe I can just copy the source code for the built-in user form and change it to my names?
Thanks a lot in advance!
Why do you need it in the auth app? Why does that matter? If you really need to do that, you can just add an app_label variable in the `Meta
class Meta:
app_label = 'auth'
This will change the table names, so you will need to migrate those.
for the ManyToManyField, I would just override the appropriate auth forms and add those fields.