Pass request.user to view without altering the url

2020-04-13 03:59发布

问题:

I'm trying to write a view where the current logged in user's information is retrieved.

My view is written as below, and it works perfectly fine as long as I pass the user to the view in the URL.

def index(request, username, template="index.html"):

    user = get_object_or_404(User,
                             username__iexact=username)

     expression_qs = Expression.objects.all().order_by('-created')
     album_qs = Album.objects.all().filter(head__isnull=False, is_public=True).order_by('-created')

    user_following = user.relationships.following()

    following_expressions = positive_filter(expression_qs, user_following, 'user')
    following_albums = positive_filter(album_qs, user_following, 'user')
    following_feed = sorted(
        chain(following_albums, following_expressions),
        key=attrgetter('created'), reverse = True)

    return render(request, template, locals())

However, as this is a view for the homepage, I would prefer to not modify the URL. I'd rather (in the template or view) describe the logic for what happens if the user if logged in or not (if they're logged in, show the activity feed, if not, simply return a static page with a log in form).

My question is, how would I pass request.user (but not through the url) to the view so that it returns the queryset for the current user?

回答1:

You don't really have to pass anything via url. You can directly access the logged in user from request.user. You can read about this over here. Also, you can check if the user is logged in using is_authentcated() method or using the login_required decorator

def ur_view(request):
   #Check if the user is logged in
   if not request.user.is_authenticated():
          #your logic if user not logged in
   else:
        #If the user is logged in


回答2:

You need the login_required decorator.

@login_required
def index(request, template="index.html"):
    user = request.user # get the currently logged in user

If the user is logged in he/she can access the activity feed otherwise they will be redirected to login page. This will make sure that only authenticated user can access this view. And you can always access the current user using request.user.



回答3:

The logged in user object is in the request object too. use: request.user

see more info in the django auth docs