Recommended: use tasks/templates/tasks/ to avoid name conflicts between applications.
Configuring Template Discovery
# settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates'], # project-level template directory
'APP_DIRS': True, # search in <app>/templates/ for each application
'OPTIONS': {
'context_processors': [...],
},
},
]
Directory Structure
mysite/
├── templates/ # DIRS — shared templates
│ └── base.html
├── tasks/
│ └── templates/ # APP_DIRS — application templates
│ └── tasks/
│ ├── list.html
│ └── detail.html
Recommended: use tasks/templates/tasks/ to avoid name conflicts between applications.
Using Templates in a View
# Path relative to DIRS or app/templates/
return render(request, 'tasks/list.html', context)
return render(request, 'base.html', context)
Template Inheritance
<!-- templates/base.html -->
<!DOCTYPE html>
<html>
<head><title>{% block title %}Site{% endblock %}</title></head>
<body>
{% block content %}{% endblock %}
</body>
</html>
<!-- tasks/templates/tasks/list.html -->
{% extends 'base.html' %}
{% block title %}Tasks{% endblock %}
{% block content %}
<h1>Task List</h1>
{% endblock %}
include — Inserting Fragments
<!-- Insert another template -->
{% include 'partials/task_card.html' with task=task %}
<!-- tasks/templates/partials/task_card.html -->
<div class="card">
<h3>{{ task.title }}</h3>
<span>{{ task.get_status_display }}</span>
</div>
Debugging Template Loading
# If a template is not found, Django raises TemplateDoesNotExist
# and lists all paths that were searched
With DEBUG=True, the error page shows the full search list.
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!