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

django-distill导出URL路径异常问题求助

问题

使用django-distill或django-bakery生成Django站点静态HTML文件时,{% static %}和{% url %}标签生成的URL无法适配静态部署的相对路径要求:

  • 根目录下的index.html中,静态资源链接为<link rel="stylesheet" href="/static/css/styles.css">,开头的斜杠导致样式表无法加载,手动移除斜杠后可正常加载
  • 嵌套子目录的页面(如country/state/destination/index.html)中,链接无法正确指向上级目录的static文件夹,需手动修改为../../static/css/styles.css才能正常加载

相关配置代码:

settings.py

STATIC_URL = "./static/"
STATIC_ROOT = BASE_DIR / "productionstatic"
STATICFILES_STORAGE = "django.contrib.staticfiles.storage.StaticFilesStorage"
DISTILL_DIR = os.path.join(BASE_DIR, "public")

app/urls.py

from django_distill import distill_path
from .models import Destination
from .views.destinations import DestinationIndex
from .views.home import HomeIndex


def get_index():
    return None

def get_destination_slug():
    for destination in Destination.objects.all():
        yield {
            "country_slug": destination.state.country.slug,
            "state_slug": destination.state.slug,
            "destination_slug": destination.slug,
        }

urlpatterns = [
    distill_path(
        "",
        HomeIndex.as_view(),
        name="home",
        distill_func=get_index,
        distill_file="index.html",
    ),

    distill_path(
        "<slug:country_slug>/<slug:state_slug>/<slug:destination_slug>/",
        DestinationIndex.as_view(),
        name="destination_index",
        distill_func=get_destination_slug,
    ),
]
解决方案

1. 开启django-distill相对URL支持

在settings.py中添加配置,让django-distill生成相对路径的URL(适配{% url %}标签):

DISTILL_RELATIVE_URLS = True

2. 自定义静态文件存储类

默认的StaticFilesStorage会生成带开头斜杠的绝对路径,需要自定义存储类来生成适配页面层级的相对路径:

在项目根目录创建storage.py文件,写入以下代码:

from django.contrib.staticfiles.storage import StaticFilesStorage
from django_distill.renderer import get_current_distill_path

class RelativeStaticFilesStorage(StaticFilesStorage):
    def url(self, name):
        url = super().url(name)
        # 移除URL开头的斜杠
        url = url.lstrip('/')
        # 获取当前生成页面的路径,计算需要回退的目录层级
        current_path = get_current_distill_path()
        if current_path:
            # 根据路径中的目录分隔符数量,添加对应的../前缀
            depth = current_path.count('/')
            url = '../' * depth + url
        return url

然后修改settings.py中的STATICFILES_STORAGE配置:

STATICFILES_STORAGE = "你的项目名.storage.RelativeStaticFilesStorage"

注意将你的项目名替换为实际的项目名称。

3. 重新生成静态文件

运行django-distill生成命令:

python manage.py distill-local

生成后的静态文件会自动适配层级:

  • 根目录index.html的静态链接为static/css/styles.css
  • 三级子目录页面的静态链接为../../static/css/styles.css

适配django-bakery的额外配置

如果使用django-bakery,在settings.py中添加:

BUILD_USE_RELATIVE_URLS = True

然后使用上述相同的自定义存储类替换STATICFILES_STORAGE,重新运行build命令即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 05:33:13