Part 6 - Connecting everything

Class-Based Views

Class-Based Views provide a structured way to handle requests in Django. Each class comes with built-in methods for specific tasks.

By inheriting from TemplateView, our Index view automatically gains access to methods like get_context_data, which allows us to send data from the database to a template using a context dictionary.

from django.views.generic import TemplateView
from .models import *    

class Index(TemplateView):
    template_name = 'news/index.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['articles'] = Article.objects.all() 
        return context

 

Template Tags

Once we include articles in the context dictionary, it becomes automatically available in the template.
Django’s template language supports logic structures like if and for to display dynamic data.

{% for article in articles %}
    {% if article.is_active %}
        <h2>{{ article.title }}</h2>
        <p>{{article.date}}</p>
        <img src="{{ article.image.url }}">
        <p>{{ article.content }}</p>
    {% endif %}
    <hr>
{% endfor %}

 

Access through the browser:
http://localhost:8000/

 


Tested with Django 5.2



12 Nov. 2025 | Last Updated: 16 Jan. 2026 | jaimedcsilva

Related
  • Part 1 - Virtual Environment
  • Part 2 - Setting up a Django Project
  • Part 3 - Templates, Views and URLs
  • Part 4 - Static and Media Files
  • Part 5 - Models and Database
  • Part 6 - Connecting everything
  • Part 7 - Publishing to the internet

  • Buy Me a Coffee