Starting with Django: Views and Templates

Today I want to talk a little about the display capabilities of Django and the apps you are creating.

Once you have created your project and your app, you are going to want to display things. The first part of this is your views. The view will help define what goes on a page.

The template is the file that help display what your views define.

Views:

The views file is how we define what information will be made available to templates we use. Views are primarily created as either class or function views. They both have their uses.

A function view is defined like a normal function:
def blog_home(request):
     posts = Post.objects.all().order_by('-created_on')
    context= {
        'posts': posts,
     }
    return render(request, 'blog/blog_home.html',context)
Where as a class function is defined as a class, and can be a lot simpler:

class PostListView(ListView):
    model = Post
    template_name = 'blog/blog_home.html'
    context_object_name = 'posts'
    ordering = ['-created_on']
Views can be as complex or as simple as you need.

Templates:

As noted earlier, the template files are html files that can include some pythonic sections like loops and variables. These use Jinja2 as a standard formatting. Key components are the loops and functions which are contained inside of a curly brace and a percentage sign

{% extends "base.html" %}
{% load static %}
{% block content %}
        <h1> About Page</h1>
{% endblock %}
As you can read by the above, we can extend other templates, using them like building blocks, we can load folders like our static folder and then embed entire blocks of code.

The block content section is extremely powerful, and is the core of the ability to extend.

Hopefully this short run through has given you a better and simpler understanding how how views and templates work together to bring your data to peoples screens.

Comments

Popular Posts