update to django 4.2;updated language switcher

This commit is contained in:
Christoph J. Scherr 2023-10-02 20:39:10 +02:00
parent 48a0d26745
commit f7f0675d26
8 changed files with 85 additions and 111 deletions

View File

@ -1,4 +1,4 @@
Django>=3.0,<4.0 Django>=4.0,<5.0
psycopg2>=2.8 psycopg2>=2.8
mysqlclient>=1.4.3 mysqlclient>=1.4.3
django_compressor>=2.2 django_compressor>=2.2

View File

@ -63,7 +63,6 @@ MIDDLEWARE = [
'django.contrib.messages.middleware.MessageMiddleware', 'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.locale.LocaleMiddleware', 'django.middleware.locale.LocaleMiddleware',
'start.middleware.LangBasedOnUrlMiddleware',
] ]
ROOT_URLCONF = 'gawa.urls' ROOT_URLCONF = 'gawa.urls'

View File

@ -21,7 +21,7 @@ from django.conf import settings
from django.conf.urls.static import static from django.conf.urls.static import static
urlpatterns = [ urlpatterns = [
re_path(r'^i18n/', include('django.conf.urls.i18n')), re_path('i18n/', include('django.conf.urls.i18n')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += i18n_patterns( urlpatterns += i18n_patterns(

View File

@ -1,26 +0,0 @@
from django.shortcuts import HttpResponse, HttpResponseRedirect
from django.utils import translation
from django.conf import settings
from django.utils.deprecation import MiddlewareMixin
from django.utils.regex_helper import re
from .forms import MainSearchForm
from .views import MainSearch
class LangBasedOnUrlMiddleware(MiddlewareMixin):
"""
used for switching the language
"""
@staticmethod
def process_request(request):
if hasattr(request, 'session'):
active_session_lang = request.session.get(
translation.LANGUAGE_SESSION_KEY)
if active_session_lang == request.LANGUAGE_CODE:
return
if any(request.LANGUAGE_CODE in language for language in settings.LANGUAGES):
translation.activate(request.LANGUAGE_CODE)
request.session[translation.LANGUAGE_SESSION_KEY] = request.LANGUAGE_CODE

View File

@ -1,62 +1,108 @@
{% load i18n %} {% load i18n %}
{% load helper_tags %}
<nav class="sticky-top navbar navbar-expand-lg navbar-dark bg-dark"> <nav class="sticky-top navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container-fluid"> <div class="container-fluid">
<a class="navbar-brand" href="{% url 'start:index' %}"> <a class="navbar-brand" href="{% url 'start:index' %}">
<img src="https://static.cscherr.de/images/profile/profile-margin.png" alt="Logo" height="30" class="d-inline-block align-text-top"> <img src="https://static.cscherr.de/images/profile/profile-margin.png"
alt="Logo"
height="30"
class="d-inline-block align-text-top">
{% translate "cscherr.de" noop %} {% translate "cscherr.de" noop %}
</a> </a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <button class="navbar-toggler"
type="button"
data-bs-toggle="collapse"
data-bs-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent"
aria-expanded="false"
aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span> <span class="navbar-toggler-icon"></span>
</button> </button>
<div class="collapse navbar-collapse" id="navbarSupportedContent"> <div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0"> <ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item dropdown"> <li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false"> <a class="nav-link dropdown-toggle"
{% translate "Start" %} href="#"
</a> role="button"
data-bs-toggle="dropdown"
aria-expanded="false">{% translate "Start" %}</a>
<ul class="dropdown-menu"> <ul class="dropdown-menu">
<li><a class="dropdown-item" href="{% url 'start:index' %}">{% translate "Start" %}</a></li> <li>
<li><a class="dropdown-item" href="{% url 'start:professional' %}">{% translate "Professionell" %}</a></li> <a class="dropdown-item" href="{% url 'start:index' %}">{% translate "Start" %}</a>
<li><a class="dropdown-item" href="{% url 'start:links' %}">{% translate "Links" %}</a></li> </li>
<li><hr class="dropdown-divider"></li> <li>
<li><a class="dropdown-item" href="{% url 'start:legal' %}">{% translate "Legal Info" %}</a></li> <a class="dropdown-item" href="{% url 'start:professional' %}">{% translate "Professionell" %}</a>
</li>
<li>
<a class="dropdown-item" href="{% url 'start:links' %}">{% translate "Links" %}</a>
</li>
<li>
<hr class="dropdown-divider">
</li>
<li>
<a class="dropdown-item" href="{% url 'start:legal' %}">{% translate "Legal Info" %}</a>
</li>
</ul> </ul>
</li> </li>
<li class="nav-item dropdown"> <li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false"> <a class="nav-link dropdown-toggle"
{% translate "Blog" %} href="#"
</a> role="button"
data-bs-toggle="dropdown"
aria-expanded="false">{% translate "Blog" %}</a>
<ul class="dropdown-menu"> <ul class="dropdown-menu">
<li><a class="dropdown-item" href="{% url 'blog:index' %}">{% translate "Start" %}</a></li> <li>
<li><a class="dropdown-item" href="{% url 'blog:browse' %}">{% translate "Browse" %}</a></li> <a class="dropdown-item" href="{% url 'blog:index' %}">{% translate "Start" %}</a>
</li>
<li>
<a class="dropdown-item" href="{% url 'blog:browse' %}">{% translate "Browse" %}</a>
</li>
</ul> </ul>
</li> </li>
<li class="nav-item dropdown"> <li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false"> <a class="nav-link dropdown-toggle"
Debug href="#"
</a> role="button"
data-bs-toggle="dropdown"
aria-expanded="false">Debug</a>
<ul class="dropdown-menu"> <ul class="dropdown-menu">
<li><a class="dropdown-item" href="http://localhost:8080" target="_blank">DB</a></li> <li>
<li><a class="dropdown-item" href="{% url 'admin:index' %}" target="_blank">Admin</a></li> <a class="dropdown-item" href="http://localhost:8080" target="_blank">DB</a>
<li><hr class="dropdown-divider"></li> </li>
<li><a class="dropdown-item" href="#">Something else here</a></li> <li>
<a class="dropdown-item" href="{% url 'admin:index' %}" target="_blank">Admin</a>
</li>
<li>
<hr class="dropdown-divider">
</li>
<li>
<a class="dropdown-item" href="#">Something else here</a>
</li>
</ul> </ul>
</li> </li>
<li class="nav-item dropdown"> <li class="nav-item dropdown">
{% get_available_languages as languages %} {% get_current_language as LANGUAGE_CODE %}
<a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false"> <form action="{% url 'set_language' %}" method="post">
{{ LANGUAGE_CODE }} {% csrf_token %}
</a> {% get_current_language as LANGUAGE_CODE %}
<ul class="dropdown-menu"> {% get_available_languages as LANGUAGES %}
{% for lang_code, lang_name in languages %} {% get_language_info_list for LANGUAGES as languages %}
<li><a class="dropdown-item" <input name="next" type="hidden" value="{{ redirect_to }}">
href="{% change_lang lang_code %}"> <a class="nav-link dropdown-toggle"
{{ lang_name }}</a></li> href="#"
{% endfor %} role="button"
<li><hr class="dropdown-divider"></li> data-bs-toggle="dropdown"
<li><a class="dropdown-item" href="#">Something else here</a></li> aria-expanded="false">{{ LANGUAGE_CODE }}</a>
</ul> <ul class="dropdown-menu">
{% for language in languages %}
<li>
<input class="dropdown-item"
type="submit"
name="language"
value="{{ language.code }}">
</li>
{% endfor %}
</ul>
</form>
</li> </li>
<li class="nav-item"> <li class="nav-item">
<button type="button" class="btn btn-dark" id="toggleThemeButton"> <button type="button" class="btn btn-dark" id="toggleThemeButton">

View File

@ -13,31 +13,3 @@ register = Library()
@register.simple_tag @register.simple_tag
def format_time(timestamp: datetime, format: str = "%F %H:%M:%S %Z") -> str: def format_time(timestamp: datetime, format: str = "%F %H:%M:%S %Z") -> str:
return timestamp.strftime(format) return timestamp.strftime(format)
@register.simple_tag(takes_context=True)
def change_lang(context, lang="de", *args, **kwargs):
"""
Get active page's url by a specified language
Usage: {% change_lang 'en' %}
shamelessly stolen from stackoverflow:
https://stackoverflow.com/a/41147772
"""
logger = logging.getLogger(__name__)
try:
path = context['request'].get_raw_uri()
url = path
try:
cur_lang: str = get_language()
url = re.sub(f"/{cur_lang}/", f"/{lang}/", url)
except Exception as e:
logger.error(f"exception while building language switcher form: {e}")
logger.debug(f"this is the context: {context}")
finally:
activate(lang)
return "%s" % url
except Exception as e:
logger.error(f"passing error chain: {e}")

View File

@ -9,6 +9,4 @@ urlpatterns = [
path("legal/", views.LegalInfo.as_view(), name="legal"), path("legal/", views.LegalInfo.as_view(), name="legal"),
path("links/", views.Links.as_view(), name="links"), path("links/", views.Links.as_view(), name="links"),
path("professional/", views.LegalInfo.as_view(), name="professional"), path("professional/", views.LegalInfo.as_view(), name="professional"),
path('language/activate/<language_code>/',
views.ActivateLanguage.as_view(), name='activate_language'),
] ]

View File

@ -8,6 +8,7 @@ from django.shortcuts import render
from django.views.generic.list import QuerySet from django.views.generic.list import QuerySet
from django.db.models import Q from django.db.models import Q
from django.views.static import loader from django.views.static import loader
from django.views import i18n
from requests import request from requests import request
from .forms import MainSearchForm from .forms import MainSearchForm
@ -57,22 +58,6 @@ class LegalInfo(TemplateView, SearchableView):
# TODO # TODO
template_name: str = "start/legalinfo.html" template_name: str = "start/legalinfo.html"
class ActivateLanguage(View):
"""
Set the language to whatever
"""
language_code = ''
redirect_to = ''
def get(self, request, *args, **kwargs):
self.redirect_to = request.META.get('HTTP_REFERER')
self.language_code = kwargs.get('language_code')
translation.activate(self.language_code)
request.session[translation.LANGUAGE_SESSION_KEY] = self.language_code
return redirect(self.redirect_to)
class MainSearch(ListView): class MainSearch(ListView):
""" """
Search for anything. Search for anything.