Views and Templates - Django Web Development Tutorial




Welcome to Part 7 of our Django web development with Python tutorial.

After we define our model, we're ready to define our blog/urls.py file, create any template we need and then we'll be done, right?! Well, traditionally, we'd also need to modify the blog/views.py before being done, but nope, we're going to employ some further Django magic and skip that part entirely with some generic views. Thus, in our blog/urls.py:

from django.conf.urls import url, include
from django.views.generic import ListView, DetailView
from blog.models import Post

urlpatterns = [ 
                url(r'^$', ListView.as_view(
                                    queryset=Post.objects.all().order_by("-date")[:25],
                                    template_name="blog/blog.html")),
            ]

Here, we are making use of the ListView, which is used mainly for a page that presents a list of something to the user. In our case, the list is going to be the last 25 blog posts ordered by date, descending (hence the - sign). Rather than writing an SQL-specific statement, we just reference our model. Because we have the backend database chosen in our settings, Django knows how to build the query in the background.

Next, we need a blog HTML page, which we've called blog/templates/blog/blog.html as per the template_name in the blog/urls.py file:

{% extends "personal/header.html" %}
{% block content %}
	{% for post in object_list %}
		<h5>{{ post.date|date:"Y-m-d" }}<a href="/blog/{{post.id}}">  {{ post.title }}</a></h5>
	{% endfor %}
{% endblock %}

Here, since it's a list, we're going to iterate through it. We'll display the post.date, in Y-m-d fashion. We then specify a dynamic URL for the specific blog itself so a user could click the link to head here. The url will lead to /blog/<postid>, and the text for the URL will be the title of the blog. We are able to reference any of the elements we've defined in the blog/models.py file.

In the next tutorial, we're going to be discussing databases and migrations.

Download the entire site's code for this tutorial here: Part 7

The next tutorial:





  • Django Web Development with Python Introduction
  • First Website - Django Web Development Tutorial
  • Jinja Templates - Django Web Development Tutorial
  • Design with HTML/CSS - Django Web Development Tutorial
  • Jinja Variables - Django Web Development Tutorial
  • Beginning a Blog - Django Web Development Tutorial
  • Views and Templates - Django Web Development Tutorial
  • Database migrations - Django Web Development Tutorial
  • Admin control panel - Django Web Development Tutorial
  • Finishing blog - Django Web Development Tutorial
  • Publishing Django Project to a web server tutorial
  • Securing Django web server with SSL - HTTPS and Lets Encrpyt