Override Get_Object() and Manually Set Pk

I have a DetailView class in which I am not passing in a pk nor a slug. Therefore, I am trying to override the get_object(self) and manually place the query filter item (in my case the user that is currently logged in). However, I am not having success:

class ViewSpecialUser(LoginRequiredMixin, DetailView):
    model = SpecialUser
    print(self)

    def get_object(self):

        object = super(ViewSpecialUser, self).get_object(queryset)
        object.queryset = queryset.filter(pk=self.request.user.pk)
        return object

    def get_context_data(self, **kwargs):
        context = super(ViewSpecialUser, self).get_context_data(**kwargs)
        return context

2 Answers

Just return instance of Model:

def get_object(self):
    return self.model.objects.get(pk=self.request.user.pk)

get_object will be called with an optional queryset parameter, which you're ignoring and you're probably getting a TypeError: get_object() takes exactly 1 argument (2 given) exception. Even if your get_object is being called without the queryset parameter in your specific situation, you're then actually trying to reference that same queryset variable that you have never defined in the first place, so you're probably getting a NameError: global name 'queryset' not defined exception.

The SingleObjectMixin's implementation of get_object sets up a default for the queryset parameter if it's not provided, and you should to the same:

def get_object(self, queryset=None):
    ...
    if queryset is None:
        queryset = self.get_queryset()
    ...

You should then use that queryset (coming either as a parameter or from self.get_queryset()) to look up your user:

    return queryset.get(pk=self.request.user.pk)

This, of course, assumes that either 1) SpecialUser is the user model used in your authentication in the first place, or 2) it has pks in sync with whatever your actual user model is.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest