Reputation: 2496
I have two users in my app so I have built a custom user by subclassing AbstractBaseUser
like this,
class MyUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
name = models.CharField(max_length=200, null=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = MyUserManager()
#other methods required here
and my users:
class User1(MyUser):
mobile_no = models.CharField(max_length=10, blank=True, null=True, validators=[validators.MinLengthValidator(10),
validators.MaxLengthValidator(10)])
profile_pic = models.ImageField(upload_to=Rename('user1_profiles'), null=True, blank=True)
about = models.TextField(null=True, blank=True)
other_details = models.TextField(null=True, blank=True)
class User2(MyUser):
mobile_no = models.CharField(max_length=10,blank=True, null=True, validators=[validators.MinLengthValidator(10),
validators.MaxLengthValidator(10)], unique=True)
avatar = models.ImageField(upload_to=Rename('profiles'), null=True, blank=True,)
This works fine, but when I try to get user using request.user
I get MyUser
instance. In some API's I would like this to be User1
and User2
in other API's. To get this working I am using this in every API:
user = User1.objects.get(id=request.user.id)
or
user = User2.objects.get(id=request.user.id)
Is there a more elegant way of doing this ? How can I stop User1 type users from accessing API's which are built for User2 type of users.
Upvotes: 0
Views: 195
Reputation: 1437
request.user will always return MyUser instance.
Add the following attribute in MyUser -
TYPES_OF_USERS = (("A", "USER1"), ("B", "USER2"))
user_type = models.Charfield(max_length=1, choices=TYPES_OF_USERS)
Then, use this code
if request.user.user_type == "A":
foo = request.user.User1.profile_pic
else:
foo = request.user.User1.avatar
As an additional note- Since mobile is common to both models, store it in the main MyUser model.
Upvotes: 1