Django Blog #14: Creating Views

by Alex
Django Blog #14: Creating Views

Let’s start by creating a view to display the list of posts. Edit the blog application’s file to 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 return(request, 
	         {'posts': posts})

This is the first Django view. The post_list view takes a request object as a single parameter. It is mandatory for all views. In this view you can retrieve all posts using the published status from the published manager that was created earlier. Finally, the render() shortcut is used. It is presented to Django to render a list of posts with a given template. This function takes a request object, a template path, and context variables to render the selected template. It returns an HttpResponce object with rendered text (usually HTML code).

The render() shortcut takes into account the context of the request, so any variable from the template context processor can be used for a given template. Context processors for templates are just callable objects that assign variables to the context. Let’s create a second view to display a single post. Add the following function to the file:

def post_detail(request, year, month, day, post) 
    post = get_object_or_404(Post, slug=post,  
   return return(request,  
		 {'post': post})

This is the post view. It takes year, month, day, and post parameters to get the published post with the given slug and date. Note that when the Post model was created, the unique_for_date field was added to the slug field. This way you can make sure that there will only be one post with such a link on a given date, which means that you can always get one specific post using the date and link (slug). This view uses the get_object_or_404() shortcut to retrieve the desired post. The function returns an object whose parameters match the request or throws an HTTP 404 (not found) exception if one was not found. At the end it uses the render() shortcut to render the resulting post using a template.

Related Posts