传递request.user以查看而不更改url [英] Pass request.user to view without altering the url
问题描述
我的观点写成如下,它的工作原理很好,只要长时间当我将用户传递到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,
following_albums = positive_filter(album_qs,user_following,'user')
follow_feed = sorted(
chain(following_albums,following_expressions),
key = attrgetter('创建'),reverse = True)
返回渲染(请求,模板,本地())
但是,由于这是主页的视图,我希望不修改URL。我宁愿(在模板或视图中)描述如果用户登录或不登录(如果他们登录,显示活动Feed)会发生什么的逻辑,如果没有,只需返回一个带有日志的静态页面我的问题是,我如何将request.user(但不是通过url)传递给视图,以便它返回当前用户的查询集?
你真的不需要通过url传递任何东西。您可以从request.user直接访问登录的用户。您可以在这里。此外,您可以使用is_authentcated()方法或使用login_required装饰器来检查用户是否登录。
def ur_view(request) :
#检查用户是否登录
如果没有request.user.is_authenticated():
#如果用户未登录
的逻辑否则:
#如果用户登录
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?
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屋!