Django Rest Framework Multyple Users

Hello, i’m having troubles to figure out how to differentiate multiple kinds of users during the login, so depending on the user type it will be redirected to one screen or another.

Let’s say two models which inherit from a Custom User:
Model User A
Model User B

After getting a token with user+password using an endpint, redirect the user to the authorized screen for him/she.

the only idea that came up to my mind was to check the user type with and endpoint using the token and then according to the info do the redirection, but i’m not sure if it’s right or not.

Thanks a lot.


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:
         if user.user_type == MyCustomUser.UserType.SUPERDUPERADMIN:
             # do something
             # 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.

1 Like

Thanks Conor, it helps a lot, in the end i set two attributes with the user type since there are only two kinds of them. Thanks for your time and advice!