In Django it is possible to change the urlpatterns dynamically.
For example the i18n module is doing this. https://docs.djangoproject.com/en/5.0/topics/i18n/translation/#translating-url-patterns
I want something similar which is changing the pattern depending on the hostname for a view.
for exmaple for www.example.com I want:
path("articles/", views.articles),
www.example.it
path("articolo/", views.articles),
www.example.de
path("artikel/", views.articles),
There should be a lookup table for each hostname and a default value if it is not defined.
How could I do this without creating a new urls.py for each hostname?
Try with Django middleware
class DynamicURLMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
host = request.get_host()
url_mappings = {
'www.example.com': 'articles',
'www.example.it': 'articolo',
'www.example.de': 'artikel',
# Add more hostnames and their corresponding patterns as needed
}
default_pattern = 'articles' # Default pattern if the hostname doesn't match
# Modify the URL pattern based on the hostname
if host in url_mappings:
request.urlconf = 'myapp.urls_' + url_mappings[host]
else:
request.urlconf = 'myapp.urls_' + default_pattern
return self.get_response(request)
from django.urls import path
from . import views
urlpatterns = [
path('articles/', views.articles, name='articles'),
# Other patterns specific to www.example.com
]
MIDDLEWARE = [
# ... other middlewares
'myapp.middleware.DynamicURLMiddleware',
# ... other middlewares
]
project/
|-- myapp/
| |-- urls_articles.py
| |-- urls_articolo.py
| |-- urls_artikel.py
| |-- ...
|
|-- myproject/
| |-- settings.py
| |-- ...
|
|-- manage.py
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With