传递 request.user 以查看而不更改 url [英] Pass request.user to view without altering the url

查看:11
本文介绍了传递 request.user 以查看而不更改 url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个检索当前登录用户信息的视图.

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

我的视图如下所示,只要我将用户传递给 URL 中的视图,它就可以正常工作.

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())

但是,由于这是主页的视图,我希望修改 URL.我宁愿(在模板或视图中)描述如果用户登录或未登录会发生什么的逻辑(如果他们登录,显示活动提要,如果没有,只需返回一个带有登录的静态页面形式).

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).

我的问题是,如何将 request.user(但不是通过 url)传递给视图,以便它返回当前用户的查询集?

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?

推荐答案

您实际上不必通过 url 传递任何内容.您可以直接从 request.user 访问登录用户.您可以通过此处.此外,您可以使用 is_authentcated() 方法或使用 login_required 装饰器检查用户是否已登录

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

这篇关于传递 request.user 以查看而不更改 url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆