Django 2 by Example
上QQ阅读APP看书,第一时间看更新

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.