Building list and detail views
Now that you have knowledge of how to use the ORM, you are ready to build the views of the blog application. A Django view is just a Python function that receives a web request and returns a web response. All the logic to return the desired response goes inside the view.
First, we will create our application views, then we will define a URL pattern for each view, and finally, we will create HTML templates to render the data generated by the views. Each view will render a template passing variables to it and will return an HTTP response with the rendered output.
Creating list and detail views
Let's start by creating a view to display the list of posts. Edit the views.py
file of your blog
application and make it look like this:
from django.shortcuts import render, get_object_or_404 from .models import Post def post_list(request): posts = Post.published.all() return render(request, 'blog/post/list.html', {'posts': posts})
You just created your first Django view. The post_list
view takes the request
object as the only parameter. Remember that this parameter is required by all views. In this view, we are retrieving all the posts with the published
status using the published
manager we created previously.
Finally, we are using the render()
shortcut provided by Django to render the list of posts with the given template. This function takes the request
object, the template path, and the context variables to render the given template. It returns an HttpResponse
object with the rendered text (normally, HTML code). The render()
shortcut takes the request context into account, so any variable set by template context processors is accessible by the given template. Template context processors are just callables that set variables into the context. You will learn how to use them in Chapter 3, Extending Your Blog Application.
Let's create a second view to display a single post. Add the following function to the views.py
file:
def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) return render(request, 'blog/post/detail.html', {'post': post})
This is the post detail view. This view takes year
, month
, day
, and post
parameters to retrieve a published post with the given slug and date. Note that when we created the Post
model, we added the unique_for_date
parameter to the slug
field. This way, we ensure that there will be only one post with a slug for a given date, and thus, we can retrieve single posts using date and slug. In the detail view, we use the get_object_or_404()
shortcut to retrieve the desired post. This function retrieves the object that matches the given parameters or launches an HTTP 404 (not found) exception if no object is found. Finally, we use the render()
shortcut to render the retrieved post using a template.
Adding URL patterns for your views
URL patterns allow you to map URLs to views. A URL pattern is composed of a string pattern, a view, and, optionally, a name that allows you to name the URL project-wide. Django runs through each URL pattern and stops at the first one that matches the requested URL. Then, Django imports the view of the matching URL pattern and executes it, passing an instance of the HttpRequest
class and keyword or positional arguments.
Create an urls.py
file in the directory of the blog
application and add the following lines to it:
from django.urls import path from . import views app_name = 'blog' urlpatterns = [ # post views path('', views.post_list, name='post_list'), path('<int:year>/<int:month>/<int:day>/<slug:post>/', views.post_detail, name='post_detail'), ]
In the preceding code, we define an application namespace with the app_name
variable. This allows us to organize URLs by application and use the name when referring to them. We define two different patterns using the path()
function. The first URL pattern doesn't take any arguments and is mapped to the post_list
view. The second pattern takes the following four arguments and is mapped to the post_detail
view:
year
: Requires an integermonth
: Requires an integerday
: Requires an integerpost
: Can be composed of words and hyphens
We use angle brackets to capture the values from the URL. Any value specified in the URL pattern as <parameter>
is captured as a string. We use path converters, such as <int:year>
, to specifically match and return an integer and <slug:post>
to specifically match a slug (a string consisting of ASCII letters or numbers, plus the hyphen and underscore characters). You can see all path converters provided by Django at https://docs.djangoproject.com/en/2.0/topics/http/urls/#path-converters.
If using path()
and converters isn't sufficient for you, you can use re_path()
instead to define complex URL patterns with Python regular expressions. You can learn more about defining URL patterns with regular expressions at https://docs.djangoproject.com/en/2.0/ref/urls/#django.urls.re_path. If you haven't worked with regular expressions before, you might want to take a look at the Regular Expression HOWTO located at https://docs.python.org/3/howto/regex.html first.
Note
Creating a urls.py
file for each app is the best way to make your applications reusable by other projects.
Now, you have to include the URL patterns of the blog
application in the main URL patterns of the project. Edit the urls.py
file located in the mysite
directory of your project and make it look like the following:
from django.urls import path,include from django.contrib import admin urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls', namespace='blog')), ]
The new URL pattern defined with include
refers to the URL patterns defined in the blog application so that they are included under the blog/
path. We include these patterns under the namespace blog
. Namespaces have to be unique across your entire project. Later, we will refer to our blog URLs easily by including the namespace, building them, for example, blog:post_list
and blog:post_detail
. You can learn more about URL namespaces at https://docs.djangoproject.com/en/2.0/topics/http/urls/#url-namespaces.
Canonical URLs for models
You can use the post_detail
URL that you have defined in the preceding section to build the canonical URL for Post
objects. The convention in Django is to add a get_absolute_url()
method to the model that returns the canonical URL of the object. For this method, we will use the reverse()
method that allows you to build URLs by their name and passing optional parameters. Edit your models.py
file and add the following:
from django.urls import reverse class Post(models.Model): # ... def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug])
We will use the get_absolute_url()
method in our templates to link to specific posts.