Django Lesson 5: Templates

🐍 Django CourseLesson 5 of 10 · 50% complete

Django templates are HTML files with special Django template language tags for displaying data, loops, and conditionals.

Template Setup

# myblog/settings.py
TEMPLATES = [{
    "DIRS": [BASE_DIR / "templates"],  # global templates dir
    # ...
}]

# Create: templates/base.html
# Create: templates/posts/list.html

Base Template

<!-- templates/base.html -->
<!DOCTYPE html>
<html>
<head>
  <title>{% block title %}My Blog{% endblock %}</title>
</head>
<body>
  <nav><a href="/">Home</a> | <a href="/posts/">Posts</a></nav>
  
  {% block content %}{% endblock %}
  
  <footer>My Blog 2024</footer>
</body>
</html>

Child Template

<!-- templates/posts/list.html -->
{% extends "base.html" %}

{% block title %}All Posts{% endblock %}

{% block content %}
  <h1>Blog Posts ({{ posts.count }})</h1>
  
  {% for post in posts %}
    <article>
      <h2><a href="/posts/{{ post.slug }}/">{{ post.title }}</a></h2>
      <p>By {{ post.author.username }} on {{ post.created_at|date:"M d, Y" }}</p>
      <p>{{ post.content|truncatewords:30 }}</p>
    </article>
  {% empty %}
    <p>No posts yet.</p>
  {% endfor %}
{% endblock %}

🏋️ Practice Task

Create a base template with navigation. Create templates for: task list (shows all tasks, grouped by project), task detail (full task info, edit link). Use template filters: |date:”Y-m-d”, |default:”No description”, |yesno:”Done,Pending”.

💡 Hint: {% for project, tasks in grouped.items %} … {% endfor %}. Group in view: from itertools import groupby

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *