是否可以访问 django 模型类中的调用者主体?
是否可以访问模型类中的用户主体?
例如,在java中,在ejb类中,ejbcontext变量始终可用,它为您提供调用者详细信息(经过身份验证的用户)
我想知道有什么方法可以在django中的模型类仅中获取它?
显然,我可以将 request.user 传递到模型类中,但这非常麻烦。
Is that possible to access user principal in model class?
For example, in java, in ejb class, there is ejbcontext variable always available which gives you caller details (authenticated user)
I am wondering are there any way to get this in django in model class only?
obviously that I can pass the request.user into model class but which is very cumbersome.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从您的问题中还不太清楚,但我猜您希望从模型实例“自动”访问当前用户。
简短的回答是否定的,这是不可能的。
由于可以从正常的请求响应流外部(例如,从 cronjob 脚本)操纵模型,因此用户甚至可能不存在。除此之外,请求和经过身份验证的用户是视图(MVC 控制器)域,而不是模型域。
最好的办法就是手动将 request.user 传递到您想要使用它们的模型方法。有 您可以使用 python 执行框架和检查模块来实现一些魔法,但显式确实比隐式要好得多。而且,正如我之前所说,request.user(甚至 request 本身)并不总是存在。
It's not too clear from your question, but I'm guessing you want "automagic" access to the current user from a model instance.
The short answer is no, it's not possible.
Since models can be manipulated from outside the normal request-response flow (for example, from a cronjob script), a user might not even exist. Aside from that, requests and authenticated users are the domain of views (MVC controllers), not models.
The best you're going to get is manually passing request.user to the model methods you want to use them in. There's some magic you can do with python execution frames and the
inspect
module, but explicit is really much better than implicit. And, like I said before, request.user (or even request itself) doesn't always exist.