Reputation: 677
I'm learning Django. I created the Sign out function. But when I loop with for it gives an error.
My Code:
def logout(request):
for key in request.session.keys():
del request.session[key]
return redirect('login')
But get this error ? I am using Python 3. Can you help me ?
RuntimeError at /logout/
dictionary changed size during iteration
Upvotes: 1
Views: 2305
Reputation: 476594
Modifying a collection over which you are iterating is tricky, and frequently not allowed. It can easily result in problems, since the iterator is usually implemented under the assumption that the collection will not change.
You however do not need to iterate over the keys here. You can use the clear()
method [Django-doc]:
def logout(request):
request.session.clear()
return redirect('login')
This is however not sufficient. Django already made a function to logout a user that will clear the session, delete it, etc. logout(..)
[Django-doc]. You thus can implement this as:
from django.contrib.auth import logout as auth_logout
def logout(request):
auth_logout(request)
return redirect('login')
Upvotes: 3