1
0
mirror of https://github.com/django/django.git synced 2025-01-08 17:37:20 +00:00

Updated docs to use cookie-based storage for timezone handling

Changed docs example from session-based to cookie-based storage for user timezone preferences, aligned with Django 4.0 which deprecated sessions for  language i18n settings.
This commit is contained in:
Rob McCombie 2023-09-24 15:10:41 +01:00
parent 574ee4023e
commit d922db3f9b
2 changed files with 7 additions and 6 deletions

View File

@ -857,6 +857,7 @@ answer newbie questions, and generally made Django that much better:
Robert Wittams Robert Wittams
Rob Golding-Day <rob@golding-day.com> Rob Golding-Day <rob@golding-day.com>
Rob Hudson <https://rob.cogit8.org/> Rob Hudson <https://rob.cogit8.org/>
Rob McCombie
Rob Nguyen <tienrobertnguyenn@gmail.com> Rob Nguyen <tienrobertnguyenn@gmail.com>
Robin Munn <http://www.geekforgod.com/> Robin Munn <http://www.geekforgod.com/>
Rodrigo Pinheiro Marques de Araújo <fenrrir@gmail.com> Rodrigo Pinheiro Marques de Araújo <fenrrir@gmail.com>

View File

@ -156,7 +156,7 @@ the time zone of their primary audience or UTC.
:func:`zoneinfo.available_timezones` provides a set of available timezones that :func:`zoneinfo.available_timezones` provides a set of available timezones that
you can use to build a map from likely locations to time zones. you can use to build a map from likely locations to time zones.
Here's an example that stores the current timezone in the session. (It skips Here's an example that stores the current timezone in cookies. (It skips
error handling entirely for the sake of simplicity.) error handling entirely for the sake of simplicity.)
Add the following middleware to :setting:`MIDDLEWARE`:: Add the following middleware to :setting:`MIDDLEWARE`::
@ -171,7 +171,7 @@ Add the following middleware to :setting:`MIDDLEWARE`::
self.get_response = get_response self.get_response = get_response
def __call__(self, request): def __call__(self, request):
tzname = request.session.get("django_timezone") tzname = request.COOKIES.get("django_timezone")
if tzname: if tzname:
timezone.activate(zoneinfo.ZoneInfo(tzname)) timezone.activate(zoneinfo.ZoneInfo(tzname))
else: else:
@ -191,11 +191,11 @@ Create a view that can set the current timezone::
def set_timezone(request): def set_timezone(request):
response = render(request, "template.html", {"timezones": common_timezones})
if request.method == "POST": if request.method == "POST":
request.session["django_timezone"] = request.POST["timezone"] tzname = request.POST["timezone"]
return redirect("/") response.set_cookie("django_timezone", tzname)
else: return response
return render(request, "template.html", {"timezones": common_timezones})
Include a form in ``template.html`` that will ``POST`` to this view: Include a form in ``template.html`` that will ``POST`` to this view: