1π
β
- I think you should use
OneToOne
relationship betweenUser
andShoppingCart
.
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)
- 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
- [Answered ]-Static fiels doesn't load in django 1.11
- [Answered ]-Why is pip installation of scipy failing in elastic beanstalk?
Source:stackexchange.com