The last thing we have to do is to create the urlpatterns
for individual blog posts, and the post.html
page.
Editing the blog/urls.py
We have the list view of our blog posts. Now let’s add the details view so we can display an individual blog post on our website. Here is the blog/urls.py
file:
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")),
url(r'^(?P<pk>\d+)$', DetailView.as_view(model = Post, template_name = "blog/post.html")),
]
The second pattern says:
url
– this is an URLr
– it is a regular expression^
– marks the beginning (after/blog
in this particular case)()
– we are capturing everything inside these parentheses?P
– it is Django named group (you can read more on Django website)<pk>
– it stands for primary key\d
– the primary key must be a digit+
– in regular expressions it means “matches one or more”\d+
– it is one or more digits$
marks the end
Creating the post.htnl
page
The post.html
will look similar to the blog.html
but in the post.html
we are going to display the entire post. Here is how the post.html
looks like:
{% extends "personal/header.html" %}
{% block content %}
<h2>{{post.title}}</h2>
<h6>posted on {{post.date}}</h6>
{{post.text | safe | linebreaks}}
{% endblock %}
Everything it is self-explanatory except for a couple of things probably:
|
means filtersafe
– allows us to put HTML in our blog posts (there are many other Jinja filters you can use)
This is how an individual blog post looks like:
This is it! We have a fully functional website with pages and blog!