I'm using Django-rest-framework
views.py:
@api_view(['GET'])
def addToCartForSession(request, pk):
product = get_object_or_404(Product, pk=pk)
if not request.session.exists(request.session.session_key):
request.session.create()
mycart, __ = Cart.objects.get_or_create(session_key=request.session.session_key)
mycart.product.add(product)
return Response({'response':'ok'})
When this function is called, it create a new key. and for new key, it create a new Cart.
But every single user should have only one cart.
So, How can I stop creating new session_key for a single user? but one session_key will be created if there is no session_key. how can i do that?
also I want to add that:
@api_view(['GET'])
def addToCartForSession(request, pk):
print(request.session.session_key) #>>> None
return Response({'response':'ok'})
when I make this, It prints None.
in my Front-end (Reactjs):
addToCart=()=>{
var id = this.props.id
var url2 = 'http://127.0.0.1:8000/addToCartForSession/'+id+'/'
fetch(url2,{
method:'GET',
headers: {
'Content-Type': 'application/json',
}
}).then(res=>res.json().then(result=>{
if(result.response === 'ok'){
this.props.dispatch({
type: 'itemInCart',
})
this.setState({addedToCart: true})
}
}))
}
this functionaddToCartForSession
called several time (when i add an item to the cart).
as long as this function called, new session_key/cart creates. but it will be only one cart for a single user.