Good evening!
I have the following, a table containing my custom users (our dear Fellows) which will serve to login our users (by using the custom model).
◢ The custom backends with it's custom user model for the Fellows table.
from django.contrib.auth.hashers import check_password
from django.contrib.auth.models import User
from .models import CustomUser
class FellowBackend:
def authenticate(self, request, **kwargs):
'''Authenticates the user (custom model).'''
# Parameters
user_id = kwargs['username']
password = kwargs['password']
# Tentatives.
try:
user = CustomUser.objects.get(id = user_id)
# If the password matches.
if check_password(password, user.password):
return user
else:
# Triggers default login failed.
return None
except CustomUser.DoesNotExist:
return None
def get_user(self, user_id):
'''TODO: Test if this override is required.'''
try:
return CustomUser.objects.get(pk = user_id)
except CustomUser.DoesNotExist:
return None
◢ The custom user model.
class Faction(models.Model):
id = models.AutoField(db_column='ID', primary_key=True) # Field name made lowercase.
name = models.CharField(db_column='Name', max_length=64) # Field name made lowercase.
class Meta:
managed = False
db_table = 'Faction'
class CustomUser(AbstractBaseUser):
id = models.PositiveBigIntegerField(db_column='ID', primary_key=True) # ID.
display_name = models.CharField(db_column='Name', max_length=64, db_collation='utf8mb4_general_ci')
password = models.CharField(db_column='User_Password', max_length=256, blank=True, null=True)
gold = models.IntegerField(db_column='Gold') # Credits.
faction = models.ForeignKey('Faction', models.RESTRICT, db_column='Faction', default=1) # ID Faction.
last_login = models.DateTimeField(db_column='Last_Login', blank=True, null=True) # Last Login.
# Admin Panel Abstract Fields
active = models.BooleanField(default=True)
staff = models.BooleanField(default=False)
USERNAME_FIELD = 'id'
REQUIRED_FIELD = [] # id (username) and password required by default.
class Meta:
managed = False
db_table = 'Fellows'
def __str__(self):
return self.display_name # Test.
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.staff
#property
def is_active(self):
"""Is the user active?"""
return self.active
So far so good, I can connect, do my stuff and even access the admin panel to manage every registered models if I am part of the staff.
However, let us say I want to add permissions between members of the staff, someone I hire for example to manage exclusively the Items table (from app Armory) while the other admin can have a total access to the models from any app.
◢ The armory app will contain the Item model (and it's references).
class Rarity(models.Model):
...
class ItemType(models.Model):
...
class Item(models.Model):
id = models.AutoField(db_column='ID', primary_key=True) # Identifier
name = models.CharField(db_column='Name', unique=True, max_length=64) # Name of the item.
description = models.TextField(db_column='Description', max_length=512, blank=True, null=True) # Description of the item.
source = models.CharField(db_column='Source', max_length=128, blank=True, null=True) # Source icon of the item.
rarity = models.ForeignKey('Rarity', models.CASCADE, db_column='Rarity') # ID of the rarity.
item_type = models.ForeignKey('ItemType', models.CASCADE, db_column='Item_Type') # ID of the item type.
item_value = models.PositiveIntegerField(db_column='Item_Value') # Value of the item.
sell = models.BooleanField(db_column='Sell') # If the item can be sold.
gift = models.BooleanField(db_column='Gift') # If the item can be sent.
dismantle = models.BooleanField(db_column='Dismantle') # If the item can be dismantled.
world = models.BooleanField(db_column='World') # If the item can be found in the world (using the bot's !wheel command).
class Meta:
db_table = 'n_rpg_items'
def __str__(self):
return self.name
◢ And an articles app that will contain the Article model.
from django.conf import settings
from django.db import models
class Article(models.Model):
id = models.AutoField(db_column='ID', primary_key=True) # ID
author = models.ForeignKey(settings.AUTH_USER_MODEL, db_column="ID_User", on_delete=models.CASCADE) # User ID
title = models.CharField(db_column='Title', max_length=32) # Title
content = models.TextField(db_column='Content') # Content
posted = models.DateTimeField(db_column='Posted') # Date Posted
source = models.CharField(db_column='Source', max_length=64, blank=True, null=True) # Source picture url of the article.
class Meta:
managed = False
db_table = 'Articles'
def __str__(self):
return 'Article : ' + self.title
To be more precise, when logging in the admin panel, admin_a will only be able to manage Items, while admin_b will be able to manage everything, Items and Articles.
The problem is, I searched for a while, the doc didn't helped me and I can't find anything that satisfies what I want to achieve so I am probably doing this wrong...
I was thinking about doing my own admin backends by adding a Role in the Fellows table but soon there will be no more use of framework if I start reinventing the wheel... :(
If anybody could share with me which solutions are conceivable, even a start, I would greatly appreciate!
Related
I have the Role model. Account model take the reference from Role model using ManytoMany Field. But, I don't want to use manytomany field. It's necessary to not use ManyToMany field. Is anyone can suggest something better.
I don't want to use use ManyToMany field because, since many to many are a Django feature and not database
The given below model works fine with ManyToMany Field, I want the same with it.
from django.db import models
from django.db.models.fields import proxy
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser
from django.utils.translation import gettext_lazy as _
from django.core.validators import RegexValidator
import uuid
from django.utils import timezone
import math
from django.core.validators import MinValueValidator, MaxValueValidator
ADMIN = 0
CUSTOMER = 1
SELLER = 2
DELIVERY_PARTNER = 4
class Role(models.Model):
'''
The Role entries are managed by the system,
automatically created via a Django data migration.
'''
ROLE_CHOICES = (
(ADMIN, 'admin'),
(CUSTOMER, 'customer'),
(SELLER, 'seller'),
(DELIVERY_PARTNER, 'delivery'),
)
id = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, primary_key=True)
def __str__(self):
return self.get_id_display()
class UserManager(BaseUserManager):
'''
creating a manager for a custom user model
https://docs.djangoproject.com/en/3.0/topics/auth/customizing/#writing-a-manager-for-a-custom-user-model
https://docs.djangoproject.com/en/3.0/topics/auth/customizing/#a-full-example
'''
def create_user(self, mobile_number, password=None):
"""
Create and return a `User` with an email, username and password.
"""
if not mobile_number:
raise ValueError('Users Must Have an email address')
user = self.model(
mobile_number=self.normalize_email(mobile_number)
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, mobile_number, password):
"""
Create and return a `User` with superuser (admin) permissions.
"""
if password is None:
raise TypeError('Superusers must have a password.')
user = self.create_user(mobile_number, password)
user.is_superuser = True
user.is_staff = True
user.save()
return user
class Account(AbstractBaseUser):
'''Account Model to store mobile number and authentication'''
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
email = models.EmailField(
verbose_name='email address',
max_length=255,
null = True,
)
type = models.ManyToManyField(Role,default=[1])
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
mobile_number = models.CharField(validators=[phone_regex], max_length=17, blank=False,null = False, unique=True)
otp = models.CharField(max_length=6, null = True, unique=True)
user_registered_on = models.DateTimeField(default=timezone.now, blank=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
USERNAME_FIELD = 'mobile_number'
REQUIRED_FIELDS = []
# Tells Django that the UserManager class defined above should manage
# objects of this type.
objects = UserManager()
def get_full_name(self):
pass
def get_short_name(self):
pass
# #property
# def is_superuser(self):
# return self.is_superuser
#property
def is_staff(self):
return self.is_superuser
def has_perm(self, perm, obj=None):
return self.is_superuser
def has_module_perms(self, app_label):
return self.is_superuser
#is_staff.setter
def is_staff(self, value):
self._is_staff = value
def __int__(self):
return self.mobile_number
def verify_user_type(self,type):
for x in self.type.all():
if x.id == type:
return True
return False
class Meta:
'''
to set table name in database
'''
db_table = "login"
I don't want to use use ManyToManyField because, since many to many are a Django feature and not database
There is nothing special about a ManyToManyField. Behind the curtains it creates a model (named appname_modename_m2mfieldname) with two ForeignKeys: one to the "source model" and one to the "target model". This is a pattern known as a junction table [wiki], which is how many-to-many relations are normally defined in a relational database.
You can even work with the "hidden" model with Account.type.through, which will return a reference to a model class.
While you can define an extra model for the junction table yourself, it makes no sense, and will only make the ORM more complicated. For more information, see the database representation section on the ManyToManyField [Django-doc].
I'm using django to create a signup platform where students can signup to weekly classes.
Each class is a django model called ClassCards which has a ManytoMany relation to User model called signed_up_student that represents all the users signed up for that class as seen below
class ClassCards(models.Model):
content = models.CharField(max_length=100, default = '')
date = models.DateField(blank=True, null = True)
time = models.TimeField(blank=True,null=True)
signed_up_students = models.ManyToManyField(User,blank=True)
full = models.BooleanField(default = False)
max_students = models.IntegerField(default=4)
teacher = models.CharField(max_length=100, default='Adi')
I would like to add a subscription option that will automatically sign up subscribed students to this weeks class. Here is my Subscription model:
class Subscriptions(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null =True)
day = models.CharField(max_length=100, choices=day_choices, null=True)
time = models.TimeField(blank=True, null=True)
num_of_times_used = models.IntegerField(default=0)
cap = models.IntegerField(default=52)
active = models.BooleanField(default= True)
expirey_date = models.DateField()
date_created = models.DateField(default = timezone.now)
To accomplish this I have created a post_save signal:
#receiver(post_save,sender=ClassCards)
def apply_subsciptions(sender,instance,created, **kwargs):
if created:
subs = Subscriptions.objects.filter(day=instance.date.strftime("%A"),
time=instance.time)
for s in subs:
instance.signed_up_students.add(s.user)
print(instance.signed_up_students.get())
The code runs properly when a ClassCards is saved without throwing any errors and the print statement prints the relevant User However when I look on the admin page, I see that there are no users in the signed_up_students field.
I Would like to understand why this isn't working as desired which should adding that user to the ManytoMany field and what is the best practice for automatically updated a ManytoMany fields.
a little modification to the class ClassCards
class ClassCards(models.Model):
signed_up_students = models.ManyToManyField(User, symmetrical=False, related_name="student_cards_students_has", blank=True)
def signed_students_list(self):
return self.signed_up_students.all()
def cards_asigned_to_student_list(self):
return self.student_cards_students_has.all()
def assign_student(self, user):
self.signed_up_students.add(user)
def unsign_user(self, user):
self.signed_up_students.remove(user)
now in the signals
#receiver(post_save,sender=ClassCards)
def apply_subsciptions(sender,instance,created, **kwargs):
if created:
subs = Subscriptions.objects.filter(day=instance.date.strftime("%A"),time=instance.time)
for s in subs:
instance.assign_student(s.user)
instance.save()
print(instance.signed_students_list())
print(instance.cards_asigned_to_student_list())
I know on this topic people asked a question before but my case is different and I have implemented almost all the solutions which I found but none of them are worked for me.
First I have defined three classes in models:
models.py
class User(AbstractBaseUser, PermissionsMixin):
""" User Model """
username = None
email = models.EmailField(max_length=255, unique=True)
name = models.CharField(max_length=255)
agency = models.ForeignKey('agency.Agency', on_delete=models.CASCADE, null=True)
weekly_email = models.NullBooleanField()
is_create_new_password = models.NullBooleanField(default=True)
is_active = models.BooleanField(default=True)
last_login_time = models.DateTimeField(null=True)
last_login_from = models.CharField(max_length=255, null=True)
created_at = models.DateField(default=timezone.now)
updated_at = models.DateField(default=timezone.now)
created_by = models.IntegerField(null=True)
updated_by = models.IntegerField(null=True)
""" The `USERNAME_FIELD` property tells us which field we will use to log in.
In this case, we want that to be the email field. """
USERNAME_FIELD = "email"
REQUIRED_FIELDS = ["username"]
""" Tells Django that the UserManager class defined above should manage
objects of this type. """
objects = UserManager()
class Role(models.Model):
""" Role Model """
name = models.CharField(max_length=255, unique=True)
class UserRole(models.Model):
""" User Role Model """
user = models.ForeignKey(User, on_delete=models.CASCADE)
role = models.ForeignKey(Role, on_delete=models.CASCADE)
Then I have defined my serializer for user module:
serializers.py
class RegistrationSerializer(serializers.ModelSerializer):
""" Serializers registration requests and creates a new user. """
user_id = serializers.IntegerField(required=False)
email = serializers.EmailField(max_length=255)
name = serializers.CharField(max_length=255)
agency_id = serializers.IntegerField(source='agency.id', required=False)
role = serializers.CharField(source='role.name')
weekly_email = serializers.NullBooleanField()
last_login_time = serializers.DateTimeField(required=False)
last_login_from = serializers.CharField(max_length=255, required=False)
class Meta:
model = User
fields = (
'role', 'user_id', 'email', 'name', 'agency_id', 'weekly_email', 'last_login_time',
'last_login_from'
)
And At the end, I have defined my view file for user creation:
views.py
class UserCreateAPIView(APIView):
""" User create Api view class """
#Allow any user (authenticated or not) to hit this endpoint.
permission_classes = (IsAuthenticated,)
serializer_class = RegistrationSerializer
def post(self, request):
""" create user using following logic. """
request.data['user_id'] = request.user.id
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save(user=request.user)
return Response({'message': response['user']['created'], 'data': serializer.data},
status=status.HTTP_201_CREATED)
Now when I run it everything works fine like user is created, role is created as per my expectations. My view, serializer and models excuted but at the end on this line:
return Response({'message': response['user']['created'], 'data': serializer.data},
status=status.HTTP_201_CREATED)
I am facing error like,
AttributeError: Got AttributeError when attempting to get a value for field `role` on serializer `RegistrationSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `User` instance.
Original exception text was: 'User' object has no attribute 'role'.
I think you need to use ModelSerializer
class RegistrationSerializer(serializers.Serializer):
to
class RegistrationSerializer(serializers.ModelSerializer):
I have an abstract model class userabstract which has fields id(primary key), name(char field) and email(email field).
I am inheriting this class in two classes user, usertemp. After signing up, i want the data to be stored in usertemp. When user clicks on confirmation mail then that data will be transferred to user class.
But whats happening is, whenever someone signs up, usertemp model is updated instead of creating a new one. Same thing is happening with user class
Here is the code for models and views
class UserAbstract(models.Model):
id = models.AutoField(db_column='ID', primary_key=True, default=1) # Field name made lowercase.
name = models.CharField(db_column='NAME', max_length=100, default='') # Field name made lowercase.
email = models.CharField(db_column='EMAIL', max_length=100, default='') # Field name made lowercase.
def __str__(self):
return self.name
class Meta:
abstract = True
#python_2_unicode_compatible
class User(UserAbstract):
def __str__(self):
return self.name ;
class Meta:
managed = True
db_table = 'User'
#python_2_unicode_compatible
class Validation(models.Model):
key = models.AutoField(primary_key=True)
key_data = models.CharField(max_length=100, default='')
create_time = models.DateTimeField()
expire_time = models.DateTimeField()
def __str__(self):
return self.key_data
#python_2_unicode_compatible
class UserTemp(UserAbstract):
validation_key = models.ForeignKey(Validation, models.DO_NOTHING, related_name='+', default='') # Field name made lowercase.
verified = models.BooleanField(default=False)
def __str__(self):
return self.validation_key.key_data
views.py
def signup(request):
if request.method == 'POST':
form = FormTemp(request.POST, request.FILES)
if form.is_valid():
primary = form.cleaned_data['email']
try:
qdict = {}
qdict['email'] = primary
user = UserTemp.objects.get(**qdict)
if user.verified==True:
return HttpResponse("Account already exists")
except:
pass
email = form.cleaned_data['email']
signer = hashlib.sha256()
signer.update(primary)
validation_key = signer.hexdigest()
confirm_key = request.build_absolute_uri('/signup-confirm/')+'?key='+validation_key
send_mail('Confirm Your Mail', confirm_key, settings.EMAIL_HOST_USER, [email,])
valid = Validation(key_data=validation_key, create_time=datetime.now(), expire_time=datetime.now()+timedelta(days=30))
valid.save()
argsdict = {}
argsdict['name'] = form.cleaned_data['name']
argsdict['email'] = form.cleaned_data['email']
argsdict['validation_key'] = valid
argsdict['verified'] = False
usertemp = UserTemp(**argsdict)
usertemp.save()
return HttpResponse("Confirmation mail sent")
else:
return HttpResponse('Invalid Data')
else:
return HttpResponse('What are you doing here ? Tresspass')
The valid.save() is working fine and every time validation key is being saved but the usertemp contains only one model and that is the most recent one.
When i tried force_insert=True then its telling me that duplicate entry exist with same primary key. As you can see, the primary key field id is AutoField then why django not creating a new model when i am writing usertemp = UserTemp(**argsdict)
The problem here is that you've given your AutoField a default value. You're telling Django to assign that field the value 1 if you don't provide it, which means that you keep writing rows with the same id.
So just get rid of that default.
The broader point to understand is that defaults are a Django-level feature, while AutoField is a database-level feature. From the perspective of the database, there's no difference between explicitly assigned column values and Django default column values.
I have a custom users schema in Django for work with roles or users type, creating an application named userprofile which will be or will setup my custom user model.
In my settings.py I have the following configuration:
INSTALLED_APPS = [
...
'userprofile',
]
#Custom model Users
AUTH_USER_MODEL = 'userprofile.User'
I customize my User class (userprofile/models.py) that inherit of the AbstractUser class for add some fields to my User model due to my requirements demanded me.
I also create these another models for roles/profile users (MedicalProfile, PatientProfile, PhysiotherapistProfile) with their own fields or attributes
In addition MedicalProfile, PatientProfile, PhysiotherapistProfile have a OneToOneField relationship with my custom model/class User so:
from __future__ import unicode_literals
from django.conf import settings
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.dispatch import receiver
from django.db.models.signals import post_save
class User(AbstractUser):
is_medical = models.BooleanField(default=False)
is_physiotherapist = models.BooleanField(default=False)
is_patient = models.BooleanField(default=False)
slug = models.SlugField(max_length=100, blank=True)
photo = models.ImageField(upload_to='avatars', null = True, blank = True)
# Overriding the save method
def save(self, *args, **kwargs):
if self.is_medical:
profile = MedicalProfile(user=self)
super(User, self).save(self, *args, **kwargs)
profile.save()
# We get the profiles user according with their type
def get_medical_profile(self):
medical_profile = None
if hasattr(self, 'medicalprofile'):
medical_profile=self.medicalprofile
return medical_profile
def get_patient_profile(self):
patient_profile = None
if hasattr(self, 'patientprofile'):
patient_profile = self.patientprofile
return patient_profile
def get_physiotherapist_profile(self):
physiotherapist_profile = None
if hasattr(self, 'physiotherapistprofile'):
physiotherapist_profile = self.physiotherapistprofile
return physiotherapist_profile
class Meta:
db_table = 'auth_user'
class MedicalProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
#active = models.BooleanField(default=True)
name = models.CharField(max_length=64)
class PatientProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
#active = models.BooleanField(default=True)
name = models.CharField(max_length=64)
class PhysiotherapistProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
#active = models.BooleanField(default=True)
name = models.CharField(max_length=64)
My Question
I want to focus my question in relation to the override process save() method:
def save(self, *args, **kwargs):
if self.is_medical:
profile = MedicalProfile(user=self)
super(User, self).save(self, *args, **kwargs)
profile.save()
I want, each that an user is created, automatically be created their profile (MedicalProfile, PatientProfile, PhysiotherapistProfile) according to if their field checked (is_medical, is_patient, is_physiotherapist)
The inconvenient that I have is with my override process is the following:
When I create an user via django admin, I get this error
I don't know about it, in relation of the reason by which is setup the user PK to None ...
What alternatives can I have for solve this situation and when I create an user, their profile instance be saved (MedicalProfile, PhysiotherapistProfile, PatientProfile) depending of the attribute checkbo/field (is_medical, is_physiotherapist , is_patient) that I choose?
I bring to all my apologies before, in case of the my question do not be suited or appropriated with the stackoverflow philosophy or by the extense of my question.
The reason that it's extense is that I want give all details for get an answer
Any orientation I will be grateful and will be appreciated
You need to do something in your save method if the user is not medical; you still need to actually save the object.
A fixed implementation would be:
def save(self, *args, **kwargs):
user = super(User, self).save(self, *args, **kwargs)
if self.is_medical:
MedicalProfile(user=self).save()
My class User located in userprofile/models.py is overriding the save method, stayed so:
class User(AbstractUser):
is_medical = models.BooleanField(default=False)
is_physiotherapist = models.BooleanField(default=False)
is_patient = models.BooleanField(default=False)
slug = models.SlugField(max_length=100, blank=True)
photo = models.ImageField(upload_to='avatars', null = True, blank = True)
def save(self, *args, **kwargs):
user = super(User, self).save( *args, **kwargs)
# Creating and user with medical, patient and physiotherapist profiles
if self.is_medical and not MedicalProfile.objects.filter(user=self).exists()\
and self.is_patient and not PatientProfile.objects.filter(user=self).exists()\
and self.is_physiotherapist and not PhysiotherapistProfile.objects.filter(user=self).exists():
medical_profile=MedicalProfile(user=self).save()
patient_profile=PatientProfile(user=self).save()
physiotherapist_profile=PhysiotherapistProfile(user=self).save()
#profile.save()
# Creating and user with medical and patient profiles
elif self.is_medical and not MedicalProfile.objects.filter(user=self).exists()\
and self.is_patient and not PatientProfile.objects.filter(user=self).exists():
medical_profile=MedicalProfile(user=self).save()
patient_profile=PatientProfile(user=self).save()
# Creating and user with medical and physiotherapist profiles
elif self.is_medical and not MedicalProfile.objects.filter(user=self).exists()\
and self.is_physiotherapist and not PhysiotherapistProfile.objects.filter(user=self).exists():
medical_profile=MedicalProfile(user=self).save()
physiotherapist_profile=PhysiotherapistProfile(user=self).save()
# Creating and user with physiotherapist and patient profiles
elif self.is_physiotherapist and not PhysiotherapistProfile.objects.filter(user=self).exists()\
and self.is_patient and not PatientProfile.objects.filter(user=self).exists():
physiotherapist_profile = PhysiotherapistProfile(user=self).save()
patient_profile = PatientProfile(user=self).save()
# Creating and user with medical profile
elif self.is_medical and not MedicalProfile.objects.filter(user=self).exists():
profile = MedicalProfile(user=self)
profile.save()
# Creating and user with patient profile
elif self.is_patient and not PatientProfile.objects.filter(user=self).exists():
profile = PatientProfile(user=self)
profile.save()
# Creating and user with physiotherapist profiles
elif self.is_physiotherapist and not PhysiotherapistProfile.objects.filter(user=self).exists():
profile = PhysiotherapistProfile(user=self)
profile.save()
# We get the profiles user according with their type
def get_medical_profile(self):
medical_profile = None
if hasattr(self, 'medicalprofile'):
medical_profile=self.medicalprofile
return medical_profile
def get_patient_profile(self):
patient_profile = None
if hasattr(self, 'patientprofile'):
patient_profile = self.patientprofile
return patient_profile
def get_physiotherapist_profile(self):
physiotherapist_profile = None
if hasattr(self, 'physiotherapistprofile'):
physiotherapist_profile = self.physiotherapistprofile
return physiotherapist_profile
# We redefine the attributes (create db_table attribute) in class Meta to say to Django
# that users will save in the same table that the Django default user model
# https://github.com/django/django/blob/master/django/contrib/auth/models.py#L343
class Meta:
db_table = 'auth_user'
class MedicalProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
#active = models.BooleanField(default=True)
name = models.CharField(max_length=64)
class PatientProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
#active = models.BooleanField(default=True)
name = models.CharField(max_length=64)
class PhysiotherapistProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
#active = models.BooleanField(default=True)
name = models.CharField(max_length=64)
# Enter the username as slug field
#receiver(post_save, sender = settings.AUTH_USER_MODEL)
def post_save_user(sender, instance, **kwargs):
slug = slugify(instance.username)
User.objects.filter(pk=instance.pk).update(slug=slug)
the save() method let me save the users with all possible combinations of profiles.
But, is there a better way to do this?