JavaScript cookie cannot be found in Django

I am trying to create a website in English and Bulgarian using the Django infrastructure. My idea is that the user should click on the button, the page will reload and the language will be changed. Here is how I am trying to do this:

In my html i hava button tag <button id='btn' onclick="changeLanguage();" type="button"> ... </button>

Excerpt from cookies.js file:

function changeLanguage() {
    if (getCookie('language') == 'EN') {
        document.getElementById('btn').innerHTML = getCookie('language');
        setCookie("language", 'BG');
    } else {
        document.getElementById('btn').innerHTML = getCookie('language');
        setCookie("language", 'EN');
    }
}

function setCookie(sName, sValue, oExpires, sPath, sDomain, bSecure) {
    var sCookie = sName + "=" + encodeURIComponent(sValue);
    if (oExpires) {
        sCookie += "; expires=" + oExpires.toGMTString();
    }
    if (sPath) {
        sCookie += "; path=" + sPath;
    }
    if (sDomain) {
        sCookie += "; domain=" + sDomain;
    }
    if (bSecure) {
        sCookie += "; secure";
    }
    document.cookie = sCookie;
}

And in my view.py file this is the situation

@base
def index(request):
    if request.session['language'] == 'EN':
        return """<b>%s</b>""" % "Home" 
    else request.session['language'] == 'BG':
        return """<b>%s</b>""" % ""

So, I know that my JS is changing the value of the language cookie, but I think Django does not understand this. On the other hand, when I set and receive a cookie in my Python code, the cookie is set. My question is, is there a way to get JS and Django to work together - JavaScript sets a cookie and Python only reads it when asked and takes appropriate action?

Thank.

+3
1

cookie.

- Django, cookie. , , .

cookie, , request.COOKIES:

if request.COOKIES['language'] == 'EN':
    return """<b>%s</b>""" % "Home" 
+8

Source: https://habr.com/ru/post/1747591/


All Articles