Home > Software design >  What is the implication of using request.user over self.request.user
What is the implication of using request.user over self.request.user

Time:12-09

I want to know the major difference between self.request.user (when using generic view View) and request.user (when using a user defined view), at times when I use django's generic View (django.views.generic import View) which has access to the django User model, I'd interact with the authenticated user as request.user and self.request.user without having any problem.

For instance, in a django views.py:

from django.contrib.auth import get_user_model

User = get_user_model()

class GetUserView(View):
    def get (self, request, *args, **kwargs):
        user_qs = User.objects.filter(username=request.user.username)
        #Do some other stuffs here


class AnotherGetUserView(View):
    def get(self, request, *args, **kwargs):
        user_qs = User.objects.filter(username=self.request.user.username)
        #Do some other stuffs here

I realize that the two queryset works fine but I can't still figure out the best to use.

CodePudding user response:

There is no difference. Before triggering the get method, it will run the .setup(…) method [Django-doc] which will set self.request = request as well as self.args and self.kwargs to the positional and named URL parameters respectively. Unless you override this, self.request will thus always refer to the same object as request, and the documentation explicitly says that you should not override the .setup(…) method without making a call to the super method which will thus set self.request.

It however does not make much sense to do User.objects.filter(username=request.user.username): you already have the user object: that is request.user, so here you will only make extra database requests. user_qs is simply a queryset with one element: request.user. You can thus for example use request.user.email to obtain the email address of the logged in user.

You might want to use the LoginRequiredMixin [Django-doc] to ensure that the view can only be called if the user has been logged in, so:

from django.contrib.auth.mixins import LoginRequiredMixin

class GetUserView(LoginRequiredMixin, View):
    
    def get (self, request, *args, **kwargs):
        # …
  • Related