After reading this blog, you will learn half of Python Django

Eraser, a funny advanced Internet bug. The new series, let us enter the world of Django together.

Finished article

Five, Python Django view

5.1 The view returns JSON data

In real work, Python Web engineers will feedback interface data to front-end engineers. The interface is generally called API. The common format of returned data is XML or JSON. Next, I will take the most common JSON format data as an example to explain in detail for you , How does Django send data from the database to the foreground.

Modify the views.pyfile.

from django.shortcuts import render
# 导入 JSON 格式数据响应类
from django.http import JsonResponse
from .models import Blog

# Create your views here.
def blog_list(request):
    blogs = Blog.objects.all()
    # 用列表生成器生成一个对象
    context = {
    
    
        "data": [{
    
    "id": blog.id, "title": blog.title} for blog in blogs]
    }
    return JsonResponse(context)

In the import header file modelsin Blogthe class, then by adding a new blog_listfunction that returns JsonResponsethe object.

5.2 Create a route

The routing-related materials will be supplemented in the future. This blog only needs to know how to return different data through different URLs.
Create a new file in the blog folder urls.py, the code content is as follows:

from django.urls import path
import blog.views as blog_views

urlpatterns = [
    path('list/', blog_views.blog_list)
]

The file writing code is completed, also need to modify my_websitethe folder in urls.pythe file, modifying the following:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('blog/', include('blog.urls')),
    path('admin/', admin.site.urls),
]

At this point your project file structure as shown below, important to note that urls.pythe file appears twice.
After reading this blog, you will learn half of Python Django
Run the current application with the following command:

python manage.py runserver

Direct access http://127.0.0.1:8000/will be out of the following error, which calls for access to a directory. Enter http://127.0.0.1:8000/adminaccess before the blog background involved input http://127.0.0.1:8000/blog/list/to get the data in JSON format.
After reading this blog, you will learn half of Python Django
The data in JSON format is as follows. Chinese has been UNICODE encoded and
After reading this blog, you will learn half of Python Django
can also be queried directly through the developer tools, just click on the blue rectangular area in the figure below.
After reading this blog, you will learn half of Python Django
After the application is completed, you can proceed with replay learning.

Accessed through the URL address, if the address is accessed /blog, it will automatically load Django urls.pyconfiguration, i.e., the following codes:

urlpatterns = [
    path('blog/', include('blog.urls')),
    path('admin/', admin.site.urls),
]

Match is found in the url blog/, then load blog.urlsthe file, the file corresponding to the code is as follows:

from django.urls import path
import blog.views as blog_views

urlpatterns = [
    path('list/', blog_views.blog_list)
]

This contains a list/matcher, so by blog/list/calling the view blog_view.blog_listfunction, which is used to return JSON-formatted data. Note blog_viewis imported viewmodules rename come, the code in the header import blog.views as blog_views.

def blog_list(request):
    blogs = Blog.objects.all()
    # 用列表生成器生成一个对象
    context = {
    
    
        "data": [{
    
    "id": blog.id, "title": blog.title} for blog in blogs]
    }
    return JsonResponse(context)

First understand the logical relationship, and then supplement the professional grammatical definition.

5.3 Extended Details Page

With the logic above, after achieving a return to a single interface blog data, first edit the views.pyfile.

def detail(request, blog_id):
    blog = Blog.objects.get(id=blog_id)

    blog = {
    
    
        "id": blog.id,
        "title": blog.title,
        "content": blog.content,
        "create_time": blog.create_time
    }
    return JsonResponse(blog)

Extended details page, found a spelling error, modify create_timeafter, pay attention to the following command sqliteto regenerate be.

> python manage.py makemigrations blog
Did you rename blog.creatr_time to blog.create_time (a DateField)? [y/N] y
Migrations for 'blog':
  blog\migrations\0002_auto_20210329_0940.py
    - Rename field creatr_time on blog to create_time

After the command is finished, run the following command:

>python manage.py migrate blog
Operations to perform:
  Apply all migrations: blog
Running migrations:
  Applying blog.0002_auto_20210329_0940... OK

Continue to modify the blogfolder urls.pyfile, the code is as follows:

from django.urls import path
import blog.views as blog_views

urlpatterns = [
    path('list/', blog_views.blog_list),
    path('detail/<int:blog_id>', blog_views.detail)
]

After the completion of the preparation of the above code, it can http://127.0.0.1:8000/blog/detail/1be a single blog data acquisition, URL address format http://127.0.0.1:8000/blog/detail/{整数序号}.

Integer number in the address, the background may be blog_idacquired, but blog_idwill be passed to the detailmethod.

The code there is a special need to explain <int:blog_id>the foregoing intis referred to as path converter, the common path converter has the following:

  • str: Match any non-empty string, the default value;
  • int: Match zero or positive integer;
  • uuid: Match a specific type of string format;
  • path: Match any non-empty character, you can match the path address, including /.

The following blogs will cover the above content, and apply them first. After all, the snowball series is a column of repeated learning.

5.4 Paging Implementation

Next, continue to blog_listmethod to expand, let it implement paging operation. Focus on views.pythe blog_list(request)methods to transform the core code reference to the following content.

from django.shortcuts import render
# 导入 JSON 格式数据响应类
from django.http import JsonResponse
# 导入分页组件
from django.core.paginator import Paginator
from .models import Blog

# Create your views here.
def blog_list(request):
    # blogs = Blog.objects.all()
    # # 用列表生成器生成一个对象
    # context = {
    
    
    #     "data": [{"id": blog.id, "title": blog.title} for blog in blogs]
    # }
    # 页码默认获取 page 参数,默认值为 1
    page = request.GET.get("page", 1)
    # 默认每页 20 条数据
    page_size = request.GET.get("page_size", 20)

    # 获取全部数据
    blog_all = Blog.objects.all()
    # 分页对象
    paginator = Paginator(blog_all, page_size)

    # 当前页码
    current_page = paginator.get_page(page)
    blogs = current_page.object_list

    context = {
    
    
        "blog_list": [{
    
    "id": blog.id, "title": blog.title} for blog in blogs],
        "paginator": {
    
    
            "total_count": paginator.count,
            "num_pages": paginator.num_pages,
            "page_size": paginator.per_page,
            "page_number": current_page.number
        }
    }

    return JsonResponse(context)

Introduced into the top of the code from django.core.paginator import Paginatorpaging means for paging the subsequent contents data by Blog.objects.all()method of acquiring in advance, the present embodiment efficiency, advanced to subsequent learning content, will be modified by the section.

After writing, the paging effect can be realized through URL related parameters. Access http://127.0.0.1:8000/blog/list/?page=1&page_size=1resulting effect is as follows:
After reading this blog, you will learn half of Python Django

5.5 Summary of this blog

This blog focuses on learning views in Django. This article is based on function-based views (FBV). In future blogs, we will learn about class-based views (CBV). Class-based views are widely used in actual development. There are also mature frameworks for using Django to develop APIs, for example Django Rest Framework.

Related Reading

  1. 100 Python crawler tutorials, great crawler tutorials, subscribe now
  2. Python game world (updated, the target number of articles is 50+, subscribe now, all are old fans)
  3. Python crawler lesson, 9 wonderful lectures

Today is the 122nd /200th day of continuous writing .
If you want to build a close relationship blogger, you can focus on the public number of the same name dream eraser , close contact with a funny senior Internet worms.
Blogger ID: Dream Eraser, I hope everyone likes , comments , and favorites .

Django WeChat applet mall Django tutorial 2020 PHP is so cool Django and spring compare Django open source project Why big companies rarely use vue python's Django framework Django how to install Django enterprise development combat pdf

Guess you like

Origin blog.csdn.net/hihell/article/details/115284224