You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django中前置站点专属模板目录并添加当前站点域名至模板目录?

How to Prepend a Site-Specific Template Directory to Django's TEMPLATES DIRS & Include the Site Domain

Great question! Let's break this down into two clear, actionable parts: prepending your site's unique template directory to the DIRS list (so it takes priority) and dynamically integrating your site's domain into that directory path.

Step 1: Define Your Site Domain

First, you need a reliable way to get your site's domain. You have two common options depending on your setup:

This is the most flexible approach, especially for production where domains might change across environments:

import os

# Pull domain from environment variable, with a fallback for local development
SITE_DOMAIN = os.environ.get("SITE_DOMAIN", "localhost:8000")

Option 2: Use Django's Sites Framework

If you're managing multiple sites with Django's built-in sites system, configure it first:

  1. Add 'django.contrib.sites' to your INSTALLED_APPS
  2. Set SITE_ID = 1 (or your site's specific ID) in settings
  3. Run migrations to create the Site model record

Then fetch the domain dynamically:

from django.contrib.sites.models import Site

# Get the current site's domain (ensure migrations are run before starting the server!)
SITE_DOMAIN = Site.objects.get_current().domain

Step 2: Create the Site-Specific Template Path

Next, build the path to your domain-specific template directory. Assuming APPS_DIR is your project's apps directory path object (common in setups like Cookiecutter Django):

# Construct the full path to your site's unique templates
SITE_TEMPLATES_DIR = str(APPS_DIR.path(f"templates/{SITE_DOMAIN}"))

Step 3: Update the TEMPLATES Configuration

Finally, prepend this site-specific directory to the DIRS list (order matters—Django checks directories left to right):

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            SITE_TEMPLATES_DIR,  # This directory gets checked FIRST
            str(APPS_DIR.path('templates')),  # Fallback to generic templates
        ],
        'OPTIONS': {
            'debug': DEBUG,
            'loaders': [
                'django.template.loaders.filesystem.Loader',
                'django.template.loaders.app_directories.Loader',
            ],
            'context_processors': [
                'django.template.context_processors.debug',
                # Add your other context processors here...
            ],
        },
    },
]

Key Notes

  • Priority Matters: By placing SITE_TEMPLATES_DIR first, Django will use domain-specific templates (e.g., templates/example.com/base.html) before falling back to generic ones (e.g., templates/base.html).
  • Directory Structure: Make sure you actually create the directory in your project (e.g., apps/templates/example.com/) for Django to find the templates.
  • Production Safety: If using the Sites framework, avoid calling Site.objects.get_current() in settings if your server starts before migrations are run—stick to environment variables for deployment.

内容的提问来源于stack exchange,提问作者bodger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:33:04