Answer the question
In order to leave comments, you need to log in
Why session breaks in django?
I create a cart, the code is something like the following, in which goods are added via ajax request
class Cart():
PurchaseInvoiceFirm = 'PurchaseInvoiceFirm'
PurchaseInvoiceCart = 'PurchaseInvoiceCart'
user = ''
def __init__(self, request):
self.user = request.user
self.check_session_vars(request)
def view_firm(self, request):
return request.session[self.PurchaseInvoiceFirm]
def view_cart(self, request):
"""Отображение корзины"""
return request.session[self.PurchaseInvoiceCart]
def add_product_to_cart(self, request, product):
"""Добавить товар в корзину"""
cart = self.PurchaseInvoiceCart
if product in request.session[cart]:
request.session[cart][product]['amoung'] += 1
else:
request.session[cart][product] = {'amoung': 1}
...
def check_session_vars(self, request):
if not self.PurchaseInvoiceFirm in request.session or not request.session[self.PurchaseInvoiceFirm]:
request.session[self.PurchaseInvoiceFirm] = 0
if not self.PurchaseInvoiceCart in request.session or not request.session[self.PurchaseInvoiceCart]:
request.session[self.PurchaseInvoiceCart] = {}
$( document ).ready(function() {
$('.cart_box').toggle(0);
get_cart()
$('.cart-link').click(function(){
$('.cart_box').toggle(400);
return false;
});
});
function get_cart() {
var token = '{{csrf_token}}';
$.ajax({
headers: { "X-CSRFToken": token },
url: '/cart/',
type: 'POST',
success: function(data) {
$(".cart_box").html(data);
$(".full_cart").html(data)
},
failure: function(data) {
alert('Не удалось');
}
});
}
function add_to_cart(id) {
let token = '{{csrf_token}}';
$.ajax({
headers: { "X-CSRFToken": token },
url: '/add-to-cart/',
type: 'POST',
data: {'id':id},
success: function(data) {
get_cart()
console.log(data)
},
failure: function(data) {
console.log('Не успешно');
}
});
}
function rem_from_cart(id) {
let token = '{{csrf_token}}';
$.ajax({
headers: { "X-CSRFToken": token },
url: '/rem-from-cart/',
type: 'POST',
data: {'id':id},
success: function(data) {
get_cart()
},
failure: function(data) {
console.log('Успешно');
}
});
}
def SetFirmSessionVar(self, request, firm):
del request.session[self.PurchaseInvoiceCart]
sessiovar = self.PurchaseInvoiceFirm
request.session[sessiovar] = firm
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question