'NoneType' 对象在我的 cart.html 在 django 中没有属性 'keys'
'NoneType' object has no attribute 'keys' in my cart.html in django
我为我的网站创建了添加到购物车的功能我现在面临的问题是当用户登录后将东西添加到购物车然后到达添加到购物车的部分加载页面并显示添加的项目但是当用户注销并再次登录该网站并直接添加到购物车页面而不添加任何项目时它显示上述错误我想每次它记录会话都清楚但我不希望它发生任何想法是什么导致了问题?
我的 views.py 购物车
class Cart(View):
def get (self, request):
ids = (list(request.session.get('cart').keys()))
sections = Section.get_sections_by_id(ids)
print(sections)
return render(request, 'cart.html', {'sections': sections})
是的,它在注销期间刷新会话。您可以查看源代码here。
要保持会话,您可以将添加的产品存储在持久内存中。也许你可以存储在数据库中。
[docs]def logout(request):
"""
Remove the authenticated user's ID from the request and flush their session
data.
"""
# Dispatch the signal before the user is logged out so the receivers have a
# chance to find out *who* logged out.
user = getattr(request, 'user', None)
if not getattr(user, 'is_authenticated', True):
user = None
user_logged_out.send(sender=user.__class__, request=request, user=user)
# remember language choice saved to session
language = request.session.get(LANGUAGE_SESSION_KEY)
request.session.flush()
if language is not None:
request.session[LANGUAGE_SESSION_KEY] = language
if hasattr(request, 'user'):
from django.contrib.auth.models import AnonymousUser
request.user = AnonymousUser()
编辑:
有多种方法可以做到这一点:
1.) 您可以将其存储在 cookie 中:Solution
2.) 使用自定义注销覆盖注销方法:
3.) 使用数据库 table 存储购物车信息。
我为我的网站创建了添加到购物车的功能我现在面临的问题是当用户登录后将东西添加到购物车然后到达添加到购物车的部分加载页面并显示添加的项目但是当用户注销并再次登录该网站并直接添加到购物车页面而不添加任何项目时它显示上述错误我想每次它记录会话都清楚但我不希望它发生任何想法是什么导致了问题?
我的 views.py 购物车
class Cart(View):
def get (self, request):
ids = (list(request.session.get('cart').keys()))
sections = Section.get_sections_by_id(ids)
print(sections)
return render(request, 'cart.html', {'sections': sections})
是的,它在注销期间刷新会话。您可以查看源代码here。 要保持会话,您可以将添加的产品存储在持久内存中。也许你可以存储在数据库中。
[docs]def logout(request):
"""
Remove the authenticated user's ID from the request and flush their session
data.
"""
# Dispatch the signal before the user is logged out so the receivers have a
# chance to find out *who* logged out.
user = getattr(request, 'user', None)
if not getattr(user, 'is_authenticated', True):
user = None
user_logged_out.send(sender=user.__class__, request=request, user=user)
# remember language choice saved to session
language = request.session.get(LANGUAGE_SESSION_KEY)
request.session.flush()
if language is not None:
request.session[LANGUAGE_SESSION_KEY] = language
if hasattr(request, 'user'):
from django.contrib.auth.models import AnonymousUser
request.user = AnonymousUser()
编辑:
有多种方法可以做到这一点:
1.) 您可以将其存储在 cookie 中:Solution
2.) 使用自定义注销覆盖注销方法:
3.) 使用数据库 table 存储购物车信息。