#How to edit my get_queryset method Django Rest to acept authenticated users and authenticated user

2 messages · Page 1 of 1 (latest)

prisma edge
#

I have this CourseViewSet which is using mixins to create,list, retrieve and update courses. Right now only authenticated users can list and retrieve courses and adminUsers can create, update courses.

The get_queryset method has been overwritten to list the courses that users have bought and all the courses.

It looks like this:

courses/views.py

def get_queryset(self):
    qs = Course.objects.filter(is_active=True, level=0)
    active_levels_prefetch = Prefetch(
        "levels",
        queryset=Level.objects.filter(is_active=True).order_by("is_special"),
    )
    qs = qs.prefetch_related("children", active_levels_prefetch)

    # Add purchased courses amount
    qs = CourseQuerySet._add_purchase_amount_to_qs(qs)

    if self.request.user.is_student():
        self._set_geolocation_params()
        qs = CourseQuerySet.list(qs, self.country)
        print(qs)

    return qs

In my util, I have this file permissions.py, to verify if users are students:

class IsStudent(BasePermission):
"""Verify is user is student."""

def has_permission(self, request, view):
    # Anonymous user aren't allowed
    if isinstance(request.user, AnonymousUser):
        return False

    return request.user.is_student()

I also edited the get_permissions method to accept unauthenticated users to get a list of the courses (look at the image)

When I tried to get all the courses without authentication, I get the next error:

AttributeError: 'AnonymousUser' object has no attribute 'is_student', which is obvious because in my get_queryset I have this line: if self.request.user.is_student(). I want to know what I can do to li all courses without authencation and at the same time list all courses and bought courses for authenticated users. I already changed the get_permissions method, what options do I have to make this happen?

slender flint
#

From a high level, change the queryset to do one type of filtering when request.user.is_authenticated is False and then what you have when they are authenticated.