From f3051d7c7a4d1dc690cd2d55da70c392445293c1 Mon Sep 17 00:00:00 2001 From: Ludwig Lohmer <ludwig.lohmer@stusta.de> Date: Tue, 17 Nov 2020 00:26:02 +0100 Subject: [PATCH] enable internalization --- vote/urls.py | 6 +++++- vote/views.py | 24 ++++++++++++++++++++++++ wahlfang/settings.py | 9 +++++++++ 3 files changed, 38 insertions(+), 1 deletion(-) diff --git a/vote/urls.py b/vote/urls.py index a2d6a68..dbc4914 100644 --- a/vote/urls.py +++ b/vote/urls.py @@ -1,5 +1,5 @@ from django.contrib.auth import views as auth_views -from django.urls import path +from django.urls import include, path from django.views.generic.base import RedirectView from vote import views @@ -10,6 +10,10 @@ urlpatterns = [ path('', views.index, name='index'), path('vote/<int:election_id>', views.vote, name='vote'), + # translation + path('i18n/', include('django.conf.urls.i18n')), + path('setlang/<lang_code>', views.setlang, name='setlang'), + # code login path('code', views.LoginView.as_view(), name='code_login'), path('code/', RedirectView.as_view(pattern_name='code_login')), diff --git a/vote/views.py b/vote/views.py index 1c3152d..871b084 100644 --- a/vote/views.py +++ b/vote/views.py @@ -3,6 +3,7 @@ from django.contrib import messages from django.contrib.auth import authenticate, login, views as auth_views from django.http.response import HttpResponseNotFound from django.shortcuts import render, redirect, get_object_or_404 +from django.utils import translation from django.utils.decorators import method_decorator from ratelimit.decorators import ratelimit @@ -153,3 +154,26 @@ def delete_own_application(request, election_id): def help_page(request): return render(request, template_name='vote/help.html') + + +def setlang(request, lang_code): + """Helper view which just sets the current language of the session + + Takes the language code as an url argument e.g. /setlang/de and redirects back + to the last URL or to the index view if no HTTP_REFERRER is available + """ + response = redirect(request.META.get('HTTP_REFERER', 'vote:index')) + + if translation.check_for_language(lang_code): + translation.activate(lang_code) + response.set_cookie( + settings.LANGUAGE_COOKIE_NAME, lang_code, + max_age=settings.LANGUAGE_COOKIE_AGE, + path=settings.LANGUAGE_COOKIE_PATH, + domain=settings.LANGUAGE_COOKIE_DOMAIN, + secure=settings.LANGUAGE_COOKIE_SECURE, + httponly=settings.LANGUAGE_COOKIE_HTTPONLY, + samesite=settings.LANGUAGE_COOKIE_SAMESITE, + ) + return response + diff --git a/wahlfang/settings.py b/wahlfang/settings.py index c556202..b3c9a35 100644 --- a/wahlfang/settings.py +++ b/wahlfang/settings.py @@ -141,6 +141,15 @@ USE_L10N = True USE_TZ = True +LANGUAGES = [ + ('en', 'EN'), + ('de', 'DE'), +] + +LOCALE_PATHS = [ + os.path.join(BASE_DIR, 'vote', 'locale'), +] + # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ -- GitLab