Multiple User Types

Hello,

I am confused on how to give permissions to different user types. In my app, we have multiple types such as builders and buyers. To access all projects listed on our website :

class ProjectViewSet(ModelViewSet):

def get_queryset(self):
if self.request and self.request.user.user_type == ‘Builder’:
builder= Builder.objects.filter(user_id = self.request.user.id).first()
return Project.objects.filter(builder= builder)
return Project.objects.all()

but this return error :
‘AnonymousUser’ object has no attribute ‘user_type’

Pls confirm.

The error is occurring because the AnonymousUser object, which represents a user who is not authenticated, does not have a user_type attribute. Therefore, you cannot access the user_type attribute on the self.request.user object when the user is not authenticated.

To avoid this error, you can first check whether the user is authenticated before accessing the user_type attribute. Here is an updated version of the get_queryset method that includes this check:

class ProjectViewSet(ModelViewSet):

    def get_queryset(self):
        if self.request.user.is_authenticated and self.request.user.user_type == 'Builder':
            builder = Builder.objects.filter(user_id=self.request.user.id).first()
            return Project.objects.filter(builder=builder)
        return Project.objects.all()

This updated version first checks whether the user is authenticated using the is_authenticated method on the self.request.user object. If the user is not authenticated, the get_queryset method simply returns all Project objects. If the user is authenticated and has a user_type attribute of “Builder”, the method filters the Project objects by the associated Builder object.

I hope this helps!