4👍
✅
You can’t set an attribute on session
object the way you’re trying to do.
But you can set a key in the session
object (since it’s just like a dictionary), like this:
# you can't set a user object directly
# because it's not JSON serializable
# but you can set its `id`
request.session['user_id'] = user.id
Later, you can get the user like this:
user_id = request.session.get('user_id', None)
if user_id:
user = User.objects.get(id=user_id)
...
To log the user out, all you have to do is delete the key from the session and call flush()
:
def logout(...):
try:
del request.session['user_id']
request.session.flush()
except KeyError:
pass
...
3👍
You have to first obtain the user through authenticate
and then call login
with the returned user
Ref: https://docs.djangoproject.com/en/2.0/topics/auth/default/#django.contrib.auth.login
Example from django’s documentation:
from django.contrib.auth import authenticate, login
def my_view(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
# Redirect to a success page.
...
else:
# Return an 'invalid login' error message.
...
- [Django]-Continue the execution of a loop after an exception is raised
- [Django]-How to read contents of zip file in memory on a file upload in python?
- [Django]-Forward declaration – no admin page in django?
Source:stackexchange.com