djangodjango-urls

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?


Solution

  • We can use the method lazy to use methods as an url pattern:

    Here is an example:

    from django.conf.urls import url
    from django.utils.translation import get_language
    from django.utils.functional import lazy
    from django.urls import path
    
    url_citylist = {
        'de': 'staedteliste',
        'pl': 'lista-miast',
        'en': 'citylist',
        ...
    }
    
    def get_pattern():
        current_language = get_language()
        if current_language in url_citylist:
            pattern = url_citylist[current_language]
        else:
            pattern = url_citylist['de']
        return pattern
    
    def city_list_url():
        return r'^' + get_pattern() + '/$'
    
    
    lazy_city_list_url = lazy(city_list_url, str)
    
    urlpatterns = [
        url(lazy_city_list_url(), views.CityListView.as_view(), name='city_list'),
    ]