官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 梨树县| 清新县| 疏附县| 桃源县| 罗田县| 长葛市| 邳州市| 廊坊市| 山西省| 宁南县| 县级市| 江源县| 静宁县| 揭东县| 游戏| 上蔡县| 乐安县| 隆德县| 浠水县| 江源县| 松滋市| 家居| 建瓯市| 武山县| 磐安县| 崇州市| 高碑店市| 平舆县| 申扎县| 佛山市| 时尚| 金乡县| 鹤山市| 宜都市| 汝州市| 雅安市| 金昌市| 贡觉县| 临洮县| 盐津县| 洱源县|