Pass request to django inherited classes

360 Views Asked by At

I am overriding some methods of a popular package, django-activity-stream (I think the package is mostly irrelevant to this question).

from app/urls.py I call TeamJSONActivityFeed

urlpatterns = [
    ...
    url(_(r'^feeds/organization/(?P<organization_id>.+)$'), TeamJSONActivityFeed.as_view(name='organization_stream')),
    ...
]

TeamJSONactivityFeed then calls 'pass', which I am not too familiar with, and inherits from two other classes, OrganizationStreamMixin and JSONActivityFeed.

from rest_framework.authentication import TokenAuthentication

class TeamJSONActivityFeed(OrganizationStreamMixin, JSONActivityFeed):
    """
    JSON feed of Activity for a custom stream. self.name should be the name of the custom stream as defined in the Manager
    and arguments may be passed either in the url or when calling as_view(...)
    """
    authentication_classes = (TokenAuthentication,)
    pass

My issue is that I cannot seem to access/pass the request object in/to these inherited classes. How would I go about passing this in? Right now, self.request.user and request.user are AnonymousUser objects.

class OrganizationStreamMixin(object):
    name = None

    def get_object(self,request):
        # this is printing Anonymous User
        pprint(str(self.request.user))
        pprint(str(request.user))
        return

    def get_stream(self):
        return getattr(Action.objects, self.name)

    def items(self, request, *args, **kwargs):
        return self.get_stream()(*args[1:], **kwargs)


class JSONActivityFeed(AbstractActivityStream, View):
    """
    Feed that generates feeds compatible with the v1.0 JSON Activity Stream spec
    """
    def dispatch(self, request, *args, **kwargs):

        for i, v in kwargs.items():
            print ("    ", i, ": ", v)

        return HttpResponse(self.serialize(request, *args, **kwargs),
                            content_type='application/json')

    def serialize(self, request, *args, **kwargs):
        pprint(str(self.request.user))

        items = self.items(request, *args, **kwargs)
        return json.dumps({
            'totalItems': len(items),
            'items': [self.format(action) for action in items]
        })

Note: I am a bit of a django/python noob, but I am sure I am calling this properly from the front end. Similar requests have access to the request user.

1

There are 1 best solutions below

6
schillingt On

I think there's a bit of confusion. You do have access to the request object otherwise it would raise an error for trying to access .user on None. If you're concerned about it being an AnonymousUser instance, then authenticate before accessing that view. If you need to prevent AnonymousUser instances from being able to access that view, then wrap the view with the login_required decorator.

Edit

You're overriding the dispatch method without calling super. That could be the problem.