0

I set the session["UserID"] for user login status in view login page after pass the verify of username and password.

Then I need to check if the user is logged in within every other views, such as home page, shopping bag page and so on.

My question is, can I check it just for one time and where should I write it? Are there some methods triggered before the views called?

Sayse
  • 42,633
  • 14
  • 77
  • 146
Simon
  • 1,033
  • 1
  • 8
  • 16
  • Possible duplicate of [Best way to make Django's login\_required the default](http://stackoverflow.com/questions/2164069/best-way-to-make-djangos-login-required-the-default) – Sayse May 17 '16 at 06:18
  • If its not the above then your question doesn't make sense, django's auth middleware handles this all for you with a `user` variable on the request – Sayse May 17 '16 at 06:19
  • @Sayse I am not use the session just for the user status. same issue with the checking session (or other flags maybe) in many views. – Simon May 17 '16 at 06:24
  • But that doesn't make sense, django handles the user state for you in its middleware so all you have to deal with is the `request.user`, or any of the other things handled in middleware – Sayse May 17 '16 at 06:26
  • @Sayse I am new in Django. I check the login status within the MASTER PAGE in ASP.NET and it can control all the other page which import it. But in Django, it's only a base.html, no backends. Give me some time to learn the middleware. – Simon May 17 '16 at 06:33

1 Answers1

3

My question is, can I check it just for one time and where should I write it?

You do check it one time, providing you are using django's built in authentication method then the whole handling of users is done for you, you don't need session user id's since django handles the user through requests with its auth middleware.

Once logged in there will be a user as part of the request object which will either be a AnonymousUser if not logged in, or an instance of your user class if you are logged in.

Are there some methods triggered before the views called?

Yes, middlewares, which you could write your own custom middleware but I don't really think you need it.

I check the login status within the MASTER PAGE in ASP.NET and it can control all the other page which import it.

I haven't really used asp.net but again, you don't need to do this, django handles its users for you (providing your using built in auth tools).

See Limiting access to logged-in users and the functions and properties available on the user class

Sayse
  • 42,633
  • 14
  • 77
  • 146