Django 检索会话用户 ID
我正在使用登录中间件创建用户登录表单。
用户成功登录后,从视图中检索用户 ID 的最佳方法是什么?
创建了一个 middleware.py:
class LoginMiddleware(object):
def process_request(self, request):
if request.path != self.require_login_path and request.user.is_anonymous():
if request.POST:
return login(request)
else:
return HttpResponseRedirect('%s?next=%s' % (self.require_login_path, request.path))
I am using login middleware to create a user login form.
What is the best method to retrieve user id from view, after user successfully login?
Created a middleware.py:
class LoginMiddleware(object):
def process_request(self, request):
if request.path != self.require_login_path and request.user.is_anonymous():
if request.POST:
return login(request)
else:
return HttpResponseRedirect('%s?next=%s' % (self.require_login_path, request.path))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
用户登录后,可以通过模板中的
request.user
自动使用其关联的User
对象。当您说“用户 ID”时,我不确定您是指用户名还是数据库中id
的字面值。不过,相同的方法适用于两者:{{ request.user.username }}
或{{ request.user.id }}
。此外,正如上面的评论者所指出的,没有理由创建新的身份验证中间件,除非您需要更改登录处理方式。否则,不要管它并使用默认值。 (这似乎是你应该根据你的中间件做的事情)。
更新:忽略提及,为了访问模板中的
request.user
,您必须传入RequestContext
。下面的render_to_response
示例:Once a user has logged in, their associated
User
object is available viarequest.user
in your template, automatically. When you say "user id", I'm not sure if you mean username or the literal value ofid
in the database. The same method applies for both, though:{{ request.user.username }}
or{{ request.user.id }}
.Additionally, as the commenter above noted, there's no reason to create a new authentication middleware unless you need to change something in how the login is processed. Otherwise, leave it alone and use the default. (Which seems to be what you should be doing based on your middleware).
UPDATE: Neglected to mention that in order to access
request.user
in your template, you must pass inRequestContext
. Examplerender_to_response
below: