【问题标题】:'NoneType' object has no attribute 'keys' in my cart.html in django'NoneType' 对象在 django 的 cart.html 中没有属性 'keys'
【发布时间】:2021-09-28 12:49:03
【问题描述】:

我为我的网站创建了添加到购物车功能我现在面临的问题是,当用户登录时将某些内容添加到购物车,然后进入 od add to cart 部分,它会加载页面并显示添加的项目,但是当用户注销并再次登录到该站点并直接添加到购物车页面而不添加任何显示上述错误的项目我猜每次它记录的会话都清楚但我不希望它发生任何想法是什么导致问题?

我的购物车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})

【问题讨论】:

  • 在设置 ids 时,检查异常并处理它们......看起来,由于会话中没有购物车,你不能在它上面使用 keys() 属性......做类似的事情当会话中没有购物车时,创建一个..
  • 这能回答你的问题吗? Persisting session variables across login

标签: django django-rest-framework django-views django-sessions


【解决方案1】:

是的,它会在注销期间刷新会话。可以查看源代码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.) 使用自定义注销覆盖注销方法:Solution

3.) 使用数据库表存储购物车信息。

【讨论】:

    猜你喜欢
    • 2021-08-03
    • 2018-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-21
    • 2018-02-11
    • 2014-10-24
    相关资源
    最近更新 更多