Reputation: 25
Im trying to start using session in django, Im trying to see the data in my session but im just getting the object reference not the data
console:
<cart.cart.Cart object at 0x7f6994753160>
views.py
def cart_view(request):
cart = Cart(request)
print(cart)
if request.user.is_authenticated:
return render(request, 'cart/cart_page.html')
else:
return redirect('account:login')
cart.py
class Cart:
def __init__(self, request):
self.session = request.session
cart = self.session.get('cart')
if not cart :
cart = self.session['cart'] = {} #cria a sessão cart
self.product = cart
Upvotes: 0
Views: 835
Reputation: 62
You can define new method like get_product- for your Cart class to get your class attribute
For example
class Cart:
def __init__(self, request):
self.session = request.session
cart = self.session.get('cart')
if not cart :
cart = self.session['cart'] = {} #cria a sessão cart
self.product = cart
def get_product(self):
return self.product
And then you can use get_product method after create new object from Cart class:
def cart_view(request):
cart = Cart(request)
print(cart.get_product()) # this line where you call your new method
if request.user.is_authenticated:
return render(request, 'cart/cart_page.html')
else:
return redirect('account:login')
or you can just override str function:
class Cart:
def __init__(self, request):
self.session = request.session
cart = self.session.get('cart')
if not cart :
cart = self.session['cart'] = {} #cria a sessão cart
self.product = cart
def __str__(self):
return f"{self.product}"
now you can just print out your cart object, it will print your product
def cart_view(request):
cart = Cart(request)
print(cart)
if request.user.is_authenticated:
return render(request, 'cart/cart_page.html')
else:
return redirect('account:login')
Upvotes: 1
Reputation: 113930
you can override the __str__
method on anyclass to control how it is converted to a string... you can also override the __repr__
method if you need to as well
class Cart:
def __init__(self, request):
self.session = request.session
cart = self.session.get('cart')
if not cart :
cart = self.session['cart'] = {} #cria a sessão cart
self.product = cart
def __str__(self):
return f"<CartObject {self.product}>"
...
print(cart)
Upvotes: 2