[django]Django:如何根据主机名动态更改 urlpatterns

· 收录于 2024-01-06 14:08:07 · source URL

问题详情

在 Django 中,可以动态更改 urlpatterns。

例如,i18n 模块正在执行此操作。 https://docs.djangoproject.com/en/5.0/topics/i18n/translation/#translating-url-patterns

我想要类似的东西,它根据视图的主机名改变模式。

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),

每个主机名都应该有一个查找表,如果未定义,则应有一个默认值。

我该怎么做?

最佳回答

尝试使用 Django 中间件

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

项目目录结构

project/
    |-- myapp/
    |    |-- urls_articles.py
    |    |-- urls_articolo.py
    |    |-- urls_artikel.py
    |    |-- ...
    |
    |-- myproject/
    |    |-- settings.py
    |    |-- ...
    |
    |-- manage.py