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

Django中通过Slug动态切换模板遇TemplateDoesNotExist错误求助

Fixing the "TemplateDoesNotExist" Error in Your Django Template Preview Feature

Hey there, let's work through why you're hitting this error and get your template preview up and running smoothly:

1. Fix the Template Include Placement & Structure

First off, your htmlbase.html has the {% include slug %} tag before the <!DOCTYPE html> declaration—this is invalid HTML and throws off Django's template loader. Plus, you're not specifying the full template path or file extension (like .html) in the include, which makes it hard for Django to find the right file.

Corrected htmlbase.html:

<!DOCTYPE html>
<html>
<head>
    <title>Template Preview</title>
</head>
<body>
    {% include slug %} <!-- Move this inside the body where your template content should render -->
</body>
</html>

2. Ensure Django Can Locate Your Preview Templates

Django looks for templates in two places: the templates directory of each installed app, or directories listed in settings.py under TEMPLATES['DIRS']. Let's make sure your setup aligns with this.

Verify Your Template Folder Structure

Assume your preview templates are organized like this (adjust to match your actual project):

your_project/
    templates/
        html/
            htmlbase.html
            preview_templates/  <!-- Create a dedicated subfolder for preview templates -->
                template_one.html
                template_two.html

Update the Slug to Use a Valid Template Path

When generating the preview button link, the slug parameter needs to be the full relative path from your templates root including the .html extension. For example, if your template is preview_templates/template_one.html, the slug should be html/preview_templates/template_one.html.

If you prefer to use just the template name (without path/extension) as the slug, modify your view to build the full path automatically:

Modified views.py:

from django.template.loader import get_template
from django.http import Http404

def template_preview(request, slug):
    # Build the full template path (adjust the folder path to match your setup)
    template_path = f"html/preview_templates/{slug}.html"
    try:
        # Check if the template exists to avoid the error
        get_template(template_path)
        context = {'template_path': template_path}
        return render(request, './html/htmlbase.html', context)
    except:
        raise Http404("Preview template does not exist")

Then update htmlbase.html to use the built path:

<!DOCTYPE html>
<html>
<head>
    <title>Template Preview</title>
</head>
<body>
    {% include template_path %}
</body>
</html>

3. Double-Check Your settings.py Template Configuration

Make sure your TEMPLATES setting points to your root templates folder so Django can find all your files:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],  # Confirm this points to your project's templates folder
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

When creating the preview button in your template list page, ensure the slug matches exactly what Django expects. For example, if using the modified view above:

<!-- In your template list page -->
<a href="{% url 'template_preview' slug='template_one' %}">Preview Template One</a>

By adjusting these parts, Django will be able to locate your preview templates and render them without the TemplateDoesNotExist error.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 14:22:39