Question

I have more then 10 languages in my website. If the user has selected one language (ex. French), if they close the browser and visit the site again, it should remain that same language (French).

How can i do this one by using cookies in jQuery?

Here is the code I currently have:

{% if request.LANGUAGE_CODE == 'da' %}
French
{% endif %}
{% if request.LANGUAGE_CODE == 'nn'
Norwegian
{% endif %}
<form action="/i18n/setlanguage/" method="post" id="language">{% csrf_token %}
<input name="languages" type="hidden" value="{{request.path}}" />
<select name="trans" onchange="this.form.submit();" 
class="lang_act">

<option value="da">French</option>
<option value="nn">Norwegian</option>

Thanks

Was it helpful?

Solution

Well, you will need to read the django docs to understand a little more about how it manages cookies and session variables: Django session.

The request in Django is a dictionary-like object that comes preloaded with several variables, but also let's you defined your own. On a view, you can set a variable to the cookies like the following:

request.cookies['lang'] = anylang

where 'lang' is the key name you want for your variable, which is gonna get set on the browser and come in the following responses, and 'anylang' is any variable you want to set for your site to work with languages, let's suppose english=1, russian=2...

At this point you set a cookie in the user browser which is going to come in the future responses, you can read the value of that cookie like this:

lang = request.cookies['lang']

and do whatever you want to do with that value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top