Django build list and detailed view

After you understand how to use ORM, you can prepare to build your application view (here I take the blog as an example). The Django view is only represented as a Python function, receiving a web request and returning a web response. In addition, all the logic for returning the response result is located in the view.

First, you need to create an application view, and then define the URL for each view. Finally, you need to create an HTML template to render the data generated by the view. Among them, each view will render a template (pass variables into it) and return an HTTP response containing the rendered output result.

Generate lists and views
Let’s start creating views to display the list of posts. Edit the views.py file of the blog application as follows:

from django.shortcuts import render, get_object_or_404
from .models import Post

def post_list(request, tag_slug=None):
    posts = Post.objects.all()
    return render(request, 'blog/post/list.html', {
    
    'posts': posts})

The above code creates the first Django view. Specifically, the post_list view receives the request object as the only parameter. It should be noted that all views need to use this parameter. In the current view, the objects manager will be used to retrieve all posts that contain the status of objects. Finally, use the render() method provided by Django to render the list of posts containing the given template.

Let's create a second view and display independent posts. For this, you can add the following functions 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})

As a post detail view, this view accepts year, month, day, and post as parameters, and retrieves published posts containing a given slug and date. Finally, use the render() method provided by Django to render the list of posts containing the given template.

Note that so far, we have only written the view, and the path and view template need to be added below. This part will be updated tomorrow. Thanks for the support.

Guess you like

Origin blog.csdn.net/Erudite_x/article/details/112588089