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:

    def get_permissions(self):
        """
        Instantiates and returns the list of permissions that this view requires.
        """
        if self.request.method == 'GET':
            permission_classes = [AllowAny]
        else:
            permission_classes = [IsAdmin]
        return [permission() for permission in permission_classes]

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?

I have tried to change the queryset 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)

    if self.request.user == IsAuthenticated : 

        # 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

   elif self.request.user != IsAuthenticated:
   #I don't know what else to do

New contributor

Marlon Ramirez is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

I personally don’t like this kind of architecture that much when you have a resource or class for anything. If you maintain this architecture, you may have code headaches or monitoring in prod, testing, and more.

I think your best option is to try to separate resources for Auth and Anon users, in case you have different business logic.

but I have a question… What do you really want to do with non-authenticating users?
show the best courses?
Show courses by country?

New contributor

JohnnyBola is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

2

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *