Reputation: 72
I am trying to write session and want to read session from another view function in django. I am using django 3.1.5. Here is my views.py code, I set a session after user is logged in request.session['value'] = 'istiak'
def loginPage(request):
if request.user.is_authenticated:
return redirect('home')
else:
if request.method == 'POST':
username = request.POST.get('username')
password =request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
request.session['value'] = 'istiak'
return redirect('home')
else:
messages.info(request, 'Username OR password is incorrect')
context = {}
return render(request, 'library_site/login.html')
And In this view I tried to get this session data. Code-> usern = request.session['value']
def bookprofile(request):
usern = request.session['value']
return render(request, 'library_site/bookprofile.html')
But I am getting error KeyError: 'value'
. Here is full error
Traceback (most recent call last):
File "C:\python\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\python\Python38\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "B:\django\Django_Project\Library\library\library_site\views.py", line 31, in bookprofile
usern = request.session['value']
File "C:\python\Python38\lib\site-packages\django\contrib\sessions\backends\base.py", line 65, in __getitem__
return self._session[key]
KeyError: 'value'
Upvotes: 2
Views: 3906
Reputation: 798
You get that error because you access a key in session
that does not exist.
You might want to consider doing some modifications to your code:
if user is not None
in your login view will always be True
, it will only return an AnonymousUser
.bookprofile
view without being logged in or having set the session['value']
value previously. You can set a default value for this by replacing the session['value']
by session.get('value', 'defaultValueHere')
. The other option would be to restrict access the bookprofile
view when not being logged in. You can achieve this by adding the decorator @login_required
on your view:from django.contrib.auth.decorators import login_required
@login_required
def bookprofile(request):
usern = request.session['value']
return render(request, 'library_site/bookprofile.html')
Upvotes: 3