Let's try an experiment. Switch the language to French, and then close the browser window. Open the browser again and visit http://127.0.0.1:8000/
. Note the absence of a language prefix in the URL. You will be redirected to the English language of the site. Wouldn't it be nice if, once you selected which language to use, it would persist across visits?
Django provides such a feature out of the box; you just have to add a few bits of code to use it. If you remember the list of steps that LocaleMiddleware
takes to determine the language for the current request, the second step—after looking at the URL for a prefix—was to look at the session. If we can put the language choice in the session dictionary, Django will automatically choose the correct language for the user on subsequent visits.
What is the correct place to put the piece of code that updates the session dictionary? If you think about it, every time the user changes their language selection, we redirect them...