I have two models one for User and another for storing CustomerInfo(user of type customer).
class User(AbstractBaseUser):
"""
This is a class for user table which overrides functionalities of default django user model.
Attributes:
name (CharField): Name of a user.
email (EmailField): Email address of a user.
mobile (CharField): Phone number of a user.
date_joined (CharField): When a user was added.
last_login (CharField): Last login date time of a user.
is_admin (CharField): If user is a admin or not.
is_active (CharField): If user is active or not.
is_staff (CharField): If user is staff or not.
is_superuser (CharField): If user is a superuser or not.
role (OneToOneField): One to one relationship with role table.
"""
name = models.CharField(max_length=80)
email = models.EmailField(max_length=255, unique=True)
mobile = models.CharField(
validators=[
RegexValidator(
regex=r"^\d{10,14}$",
message="Phone number must be entered in format: '+999999999'. Up to 14 digits allowed.",
)
],
max_length=15,
unique=True,
)
role = models.ForeignKey(Role, on_delete=models.SET_NULL, null=True)
drivers = models.ManyToManyField(
"self", through="DispatcherDriver", symmetrical=False
)
date_joined = models.DateTimeField(auto_now_add=True)
last_login = models.DateTimeField(auto_now=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)
created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True)
updated_at = models.DateTimeField(auto_now=True, null=True, blank=True)
USERNAME_FIELD = "mobile"
REQUIRED_FIELDS = ["email", "name"]
objects = UserManager()
class Meta:
db_table = "users"
def __str__(self):
return self.name
# For checking permissions. to keep it simple all admin have ALL permissons
def has_perm(self, perm, obj=None):
return self.is_admin
# Does this user have permission to view this app? (ALWAYS YES FOR SIMPLICITY)
def has_module_perms(self, app_label):
return True
#receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
class CustomerInfo(models.Model):
customer = models.OneToOneField(
User, on_delete=models.CASCADE, primary_key=True, related_name="customer_info"
)
company_name = models.CharField(max_length=255)
class Meta:
db_table = "customer_info"
def __str__(self):
return self.company_name
CustomerInfo model has OneToOneField mentioned in the model. How can I access CustomerInfo of a User model using reverse relationship?
Suppose, you has User's instance user then you can fetch customer_info as
from django.core.exceptions import ObjectDoesNotExist
try:
customer_info = user.customer_info
except ObjectDoesNotExist:
print("There is no customer info here.")
Reference - https://docs.djangoproject.com/en/3.1/topics/db/examples/one_to_one/
Try:
myuser = User.objects.create(email="..", name="..", password="1223")
profile = CustomerInfo.objects.create(customer=myuser)
company_name = myuser.customer_info.company_name
Related
I want to add a user to a group after the user object is saved. Each user has a user type corresponding to the group the user belongs to. For example, if the user_type is 2, then the user belongs to Group_3, and so on.
This is my code:
class User(AbstractBaseUser, PermissionsMixin):
""" Custom user model """
USER_TYPE = ((1, 'HOD'), (2, 'Staff'), (3, 'Student'))
email = models.EmailField(
_("Email Address"),
max_length=255,
unique=True,
help_text="Ex: example#example.com",
)
eec = models.ForeignKey(
EEC, on_delete=models.CASCADE, null=True, related_name='eec',blank=True)
is_staff = models.BooleanField(_("Staff status"), default=False)
is_active = models.BooleanField(_("Active"), default=True)
date_joined = models.DateTimeField(_("Date Joined"), auto_now_add=True)
last_updated = models.DateTimeField(_("Last Updated"), auto_now=True)
user_type = models.IntegerField(default=1, choices=USER_TYPE)
lastName = models.CharField(default='', max_length=250)
firstName = models.CharField(default='', max_length=250)
objects = UserManager()
USERNAME_FIELD = "email"
def __str__(self):
return self.email
class Teacher(models.Model):
admin = models.OneToOneField(User, on_delete=models.CASCADE)
#receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
if instance.user_type == 1:
Admin.objects.create(admin=instance)
if instance.user_type == 2:
try:
Teacher.objects.create(admin=instance)
g1 = Group.objects.get(name='teacher')
instance.groups.add(g1)
except:
print("Exception")
if instance.user_type == 3:
Student.objects.create(admin=instance)
Basically, when I save the user model with a user type of 2, the group does not get updated
class FutsalUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(verbose_name='email address', max_length=255, unique=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(
_('staff status'),
default=True,
help_text=_('Designates whether the user can log into this admin site.'),
)
objects = FutsalUserManager()
USERNAME_FIELD = 'email'
def __str__(self):
return self.email
#property
def company_details(self):
company_data = Company.objects.filter(user= self)
if company_data :
company_data.name
return company_data
else:
return None
class Company(TimeStampedModel):
name = models.CharField(max_length=200)
hr_name = models.CharField(max_length=200)
hr_email = models.CharField(max_length=200)
user = models.ForeignKey(
settings.AUTH_USER_MODEL, models.DO_NOTHING)
hr_verified = models.BooleanField(default=False, blank=True)
primary_phone = models.CharField(null=True, max_length=200)
followed_by = models.CharField(max_length=200,default="Not assigned")
comments = models.TextField(default="")
def __str__(self):
return self.name
1. There is no need to create a custom function in Model, to fetch other values of other table which are in relation.
[ 1 ] you should have a related_name in your company user table. like
user = models.ForeignKey(
settings.AUTH_USER_MODEL, models.DO_NOTHING, related_name='company')
# you can name company with something of your own choice.
# following will be more appropriate.
user = models.ForeignKey(
FutsalUser, models.DO_NOTHING, related_name='company')
[ 2 ] once you have a related_name, you can fetch the companies values as following.
FutsalUser.objects.all().values('email', 'is_active', 'company__name', 'company__hr_email')
2. Apart from that you can fetch the details from Company table instead.
Company.objects.all().values('name', 'user__email') # you can add more field if you want.
3
users = FatalUser.objects.all()
for user in users:
company_list = user.company_details
# this company_list will have the companies associated with user.
print(company_list)
for company in company_list:
print(company.name, company.hr_email)
I want to check that the card number is exists and then get the associated user to that card number. A user can have multiple card numbers. How do I filter to get the user from the card number entered?
Models:
class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(
verbose_name="Email Field", max_length=60, unique=True)
dateJoined = models.DateTimeField(
verbose_name="Date Joined", auto_now_add=True)
last_login = models.DateTimeField(verbose_name="Last Login", auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_superuser = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_verified = models.BooleanField(default=False)
# Parameters that we want to know about the user
first_name = models.CharField(verbose_name="First Name", max_length=100)
last_name = models.CharField(verbose_name="Lasst Name", max_length=100)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']
objects = CustomUserManager()
def __str__(self):
return self.email
def tokens(self):
refresh = RefreshToken.for_user(self)
return {
'refresh': str(refresh),
'access': str(refresh.access_token)
}
def has_perm(self, perm, obj=None):
return self.is_superuser
def has_module_pers(self, app_label):
return True
class cardModel(models.Model):
user = models.ForeignKey(CustomUser, related_name='card_numbers',null = True, blank=True, on_delete=models.CASCADE)
card_number = models.IntegerField(
verbose_name="Card Number", blank=True, null=True, default=None, unique=True)
def __int__(self):
return self.card_number
Serializer:
class CheckCard(serializers.Serializer):
card_number = serializers.IntegerField(write_only=True)
class Meta:
fields = ['card_number','user']
read_only_fields = ['user']
Views:
class CheckCardAPI(APIView):
permission_classes = [AllowAny]
serializer_class = CheckCard
def post(self,request,*args,**kwargs):
serializer = self.serializer_class(data=request.data)
card_number = request.data.get('card_number','')
if cardModel.objects.filter(card_number=card_number).exists():
user = User.objects.filter(card_numbers=card_number)
tokens, created = Token.objects.get_or_create(user=user)
return Response({'token':tokens.key},status=status.HTTP_200_OK)
else:
return Response({'error':'card is not registered'},status=status.HTTP_404_NOT_FOUND)
You are looking for a single user based on card number, so your query
user = User.objects.filter(card_numbers=card_number)
returns a list. Maybe you would need to use
user = User.objects.get(card_numbers=card_number)
to get an object or use
value_list(id, flat=True)
with filter.
I created a custom User model with multiple roles customers, and employees, where employees also are in different roles: Drivers and administration.
I extended AbstractBaseUser model class to set a customized user model as this:
class UserAccountManager(BaseUserManager):
def create_superuser(self, email, first_name, last_name, password, **other_fields):
other_fields.setdefault("is_staff", True)
other_fields.setdefault("is_superuser", True)
other_fields.setdefault("is_active", True)
other_fields.setdefault("is_driver", True)
other_fields.setdefault("is_customer", True)
other_fields.setdefault("is_responsable", True)
if other_fields.get("is_staff") is not True:
raise ValueError(_("Superuser must be assigned to is_staff."))
if other_fields.get("is_superuser") is not True:
raise ValueError(_("Superuser must be assigned to is_superuser."))
return self.create_user(email, first_name, last_name, password, **other_fields)
def create_user(self, email, first_name, last_name, password, **other_fields):
if not email:
raise ValueError(_("You must provide an email address"))
email = self.normalize_email(email)
user = self.model(email=email, first_name=first_name, last_name=last_name, **other_fields)
user.set_password(password)
user.save()
return user
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_("Email Address"), unique=True)
first_name = models.CharField(_("First Name"), max_length=150, unique=True)
last_name = models.CharField(_("Last Name"), max_length=150, unique=True)
mobile = models.CharField(_("Mobile Number"), max_length=150, blank=True)
is_active = models.BooleanField(_("Is Active"), default=False)
is_staff = models.BooleanField(_("Is Staff"), default=False)
is_driver = models.BooleanField(_("Is Driver"), default=False)
is_responsable = models.BooleanField(_("Is Responsable"), default=False)
is_customer = models.BooleanField(_("Is Customer"), default=False)
created_at = models.DateTimeField(_("Created at"), auto_now_add=True, editable=False)
updated_at = models.DateTimeField(_("Updated at"), auto_now=True)
objects = UserAccountManager()
USERNAME_FIELD = "email"
REQUIRED_FIELDS = ["first_name", "last_name"]
class Meta:
verbose_name = "Account"
verbose_name_plural = "Accounts"
def __str__(self):
return self.first_name
and I created two types of models the extend this model which represent each on a different role and inherit from User model:
class Employee(User):
registration_number = models.PositiveSmallIntegerField(_("Driver Registration Number"), unique=True)
picture = models.ImageField(
verbose_name=_("Driver Pic"), help_text=_("Driver Identity Picture"), upload_to="images/driver/"
)
birth_date = models.DateField(_("Date Birth of the Driver"))
city_id = models.ForeignKey("City", blank=True, null=True, on_delete=models.SET_NULL)
bank_id = models.ForeignKey("Bank", blank=True, null=True, on_delete=models.SET_NULL)
class Meta:
verbose_name = "Employee"
verbose_name_plural = "Employees"
def __str__(self):
return self.first_name + " " + self.last_name
class Customer(User):
company_name = models.CharField(_("Company Name"), max_length=150, unique=True)
website = models.CharField(_("Company website"), max_length=150, unique=True)
mobile_2 = models.CharField(_("Mobile Number"), max_length=150, blank=True)
class Meta:
verbose_name = "Customer"
verbose_name_plural = "Customers"
def __str__(self):
return self.first_name + " " + self.last_name
I want to register the models in the admin.py:
#admin.register(User)
class UserAdmin(admin.ModelAdmin):
pass
admin.site.register(Customer)
admin.site.register(Employee)
the problem is that, when I try to add a user from the admin page, I can't set a password for this user, I have a password field that appear when I want to add a new user in any model, but the field seems to be as any normal InputText, the password is visible when it's tapped, and no password is registered in the database.
I would like to add two type of Employee in the model.py :
class Responsable(Employee):
responsability_type = models.CharField(max_length=4, blank=True)
class Meta:
verbose_name = "Responsable"
verbose_name_plural = "Responsables"
def __str__(self):
return self.first_name + " " + self.last_name
class Driver(Employee):
driving_licence = models.ImageField(
verbose_name=_("Driver Licence"), help_text=_("Driver Licence Picture"), upload_to="images/driver_licence/"
)
driver_licence_expiration_date = models.DateField(_("Expiration Date for Driver Licence"))
class Meta:
verbose_name = "Driver"
verbose_name_plural = "Drivers"
def __str__(self):
return self.first_name + " " + self.last_name
I don't know if it's a good idea to design this models for this kind of roles, I want to avoid getting multiple tables with passwords stored in it.
Don' t use model inheritance like that, especially for the custom User model. Creates a unique model that inherits from AbstractBaseUser, that contains the type of the user and that contains all the fields that you have declared in your current tables:
class User(AbstractBaseUser, PermissionsMixin):
class UserTypes(Enum):
customer = ('cu', 'Customer')
responsable = ('re', 'Responsable')
driver = ('dr', 'Driver')
#classmethod
def get_value(cls, member):
return cls[member].value[0]
user_type = models.CharField(max_length=2, choices=[x.value for x in UserTypes])
# Insert fields that are in common between all user types, for example:
email = models.EmailField(_("Email Address"), unique=True)
# Insert fields that could be None depending on the user type, for example:
company_name = models.CharField(_("Company Name"), max_length=150, unique=True, null=True, blank=True)
Then add this in your settings:
AUTH_USER_MODEL = 'yourappname.User'
Your ModelAdmin for managing users should inherit from UserAdmin to allow password management:
#admin.register(User)
class UserAdmin(UserAdmin):
fieldsets = ((None, {'fields': ('email', 'password', 'user_type', 'company_name')})) # Other fields showed when updating an user
add_fieldsets = ((None, {'fields': ('email', 'password', 'user_type', 'company_name')})) # Other fields showed when creating an user
Trying to make a password reset view. I'm using the auth_views built in views ie PasswordResetView and PasswordResetConfirmView for resetting password. However I was getting this error
Cannot resolve keyword 'is_active' into field. Choices are: active, admin, email, first_name, id, last_login, last_name, logentry, password, staff, timetables
. Tried changing active to is_active and getting this error.
django.core.exceptions.FieldError: Unknown field(s) (active) specified for User
Not able to make migrations
models.py
class User(AbstractBaseUser):
first_name = models.CharField(max_length=50, blank=True, null=True)
last_name = models.CharField(max_length=50, blank=True, null=True)
email = models.EmailField(max_length=254, unique=True)
is_active = models.BooleanField(default=True)
staff = models.BooleanField(default=False)
admin = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = UserManager()
def __str__(self):
return self.email
def get_first_name(self):
if self.first_name:
return self.first_name
return self.email
def get_last_name(self):
return self.last_name
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
#property
def is_staff(self):
return self.staff
#property
def is_admin(self):
return self.admin
#property
def is_active(self):
return self.is_active
forms.py
class UserAdminChangeForm(forms.ModelForm):
"""A form for updating users. Includes all the fields on
the user, but replaces the password field with admin's
password hash display field.
"""
password = ReadOnlyPasswordHashField()
class Meta:
model = User
fields = ('email', 'first_name', 'last_name',
'password', 'active', 'admin')
def clean_password(self):
# Regardless of what the user provides, return the initial value.
# This is done here, rather than on the field, because the
# field does not have access to the initial value
return self.initial["password"]
Try to change is_active = models.BooleanField(default=True) to active = models.BooleanField(default=True) in your User class, and is_active property
see below
class User(AbstractBaseUser):
first_name = models.CharField(max_length=50, blank=True, null=True)
last_name = models.CharField(max_length=50, blank=True, null=True)
email = models.EmailField(max_length=254, unique=True)
active = models.BooleanField(default=True)
staff = models.BooleanField(default=False)
admin = models.BooleanField(default=False)
#property
def is_active(self):
return self.active