[Answered ]-None Type Error Attribute

1πŸ‘

βœ…

  1. I think you should use OneToOne relationship between User and ShoppingCart.

Sample model:

class Listener(User):
   name = models.CharField(max_length=200, blank=True, null=True)
   bio = models.TextField(blank=True, null=True)
   cart = models.OneToOneField(ShoppingCart, blank=True, null=True)
  1. In your view create a cart for user if it does not exists

As

def add_to_cart(request):
    if not request.user.is_authenticated() or not request.method == 'POST':
       return HttpResponse(json.dumps({'success':False}), content_type='application/json')
    typeobj = request.POST.get('type', None)
    obj = request.POST.get('id', None)
    if typeobj is None or obj is None:
        return HttpResponse(json.dumps({'success':False}), content_type='application/json')

    if request.usr.listener.cart == None:
         cart = ShoppingCart()
         cart.save()
         request.usr.listener.cart = cart
         request.usr.listener.save()

    # your code to add items in cart
πŸ‘€Rohan

1πŸ‘

request.user is an instance of the User object of the currently logged in user.

There is no relation between your Listener model and the User model (even though you inherited from it), so whatever you are trying to do, it won’t work. In fact, even if there was a relationship, you’d be seeing these errors because you are not using the object relations correctly.

If you want to track a shopping cart for each user permanently, you need to add a ForeignKey to your ShoppingCart model to point to the User model.

If you just want to track the cart for a session; then use sessions to do so.

It might benefit you from going through the relations section of the documentation, since you aren’t using add() correctly either.

πŸ‘€Burhan Khalid

Leave a comment