Hi,
A common way of having multiple user types is to use choices.
class MyCustomUser(models.Model):
class UserType(models.TextChoices):
ADMIN = "ADM", "Admin "
SUPERADMIN = "SUP", "Super Admin"
SUPERDUPERADMIN = "SUPDU", "Super Duper Admin"
user_type = models.CharField(
max_length=50, choices=UserType.choices, default=UserType.ADMIN, unique=False
)
Choices Docs
One approach is to authenticate and assign the authenticated user to a variable in your authentication view. In the below example, authenticating_user
is the result of calling your my_call_to_authentication()
A successful authentication could return a user or a userid. Once you have the user, you can query the user type.
authenticating_user = my_call_to_authentication()
if authenticating_user.is_authenticated:
try:
if user.user_type == MyCustomUser.UserType.SUPERDUPERADMIN:
# do something
else:
# do something else
except user_model.DoesNotExist:
There are other ways of doing this, for example, a userid
might be in the return data to the frontend, so you could use that information to fetch the user from the DB. If this information is not present in the response, then you can look to the above idea. There might be better ways of doing it, but this at least gives you an idea of what can be done.
You can also access the request from a serializer’s context in your serializer methods. Here’s an example of assigning a model’s created_by
attribute to the user making the request.
class MySerializer(serializers.ModelSerializer():
def save(self, **kwargs):
request = self.context.get("request")
if request and hasattr(request, "user"):
kwargs["created_by"] = request.user
return super().save(**kwargs)
I’m a bit light on words and details today, but hopefully this will get you moving in the right direction.