A
A
AlexNest2021-05-27 15:57:51
Django
AlexNest, 2021-05-27 15:57:51

Why session breaks in django?

I create a cart, the code is something like the following, in which goods are added via ajax request

spoiler

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] = {}


The ajax request itself:
spoiler

$( 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('Успешно');
            }
        });

    }


ybSTrbXHwRk.jpg?size=537x164&quality=96&sign=4a7676d68fca5a4d69623daed626aadb&type=album
And everything seems to work, the data is updated, everything is fine, but in addition to this, you need to save the company ID in the session (while clearing the trash):
spoiler

def SetFirmSessionVar(self, request, firm):
        del request.session[self.PurchaseInvoiceCart]
        sessiovar = self.PurchaseInvoiceFirm
        request.session[sessiovar] = firm


And then everything breaks - the session with the basket is no longer updated (even if you do not delete it)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
AlexNest, 2021-05-27
@AlexNest

It was necessary to register in the settings: or after the change
SESSION_SAVE_EVERY_REQUEST = True

...
request.session.modified

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question