Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How to dynamically change urlpatterns based on the hostname

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?

like image 813
Philipp S. Avatar asked Dec 29 '25 06:12

Philipp S.


1 Answers

Try with Django middleware

myapp/middleware.py

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)

myapp/urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('articles/', views.articles, name='articles'),
    # Other patterns specific to www.example.com
]

settings.py

MIDDLEWARE = [
    # ... other middlewares
    'myapp.middleware.DynamicURLMiddleware',
    # ... other middlewares
]

Project directory structure

project/
    |-- myapp/
    |    |-- urls_articles.py
    |    |-- urls_articolo.py
    |    |-- urls_artikel.py
    |    |-- ...
    |
    |-- myproject/
    |    |-- settings.py
    |    |-- ...
    |
    |-- manage.py
like image 99
Mahammadhusain kadiwala Avatar answered Dec 30 '25 22:12

Mahammadhusain kadiwala



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!