0

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
devharb
  • 211
  • 2
  • 4

1 Answers1

1

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.

eternicode
  • 6,805
  • 4
  • 33
  • 39