Eraser, a funny advanced Internet bug. The new series, let us enter the world of Django together.
Finished article
- Snowball learning Python third round, the world of Django on the Python Web
- With a little hand shaking, you can use Python Django to implement a micro blog system
- Django is a small backend, the details are being perfected a little bit, snowballing to learn Python third stage
- Django QuerySet just learn a little bit, a little bit is enough
Snowball Learn Python Round 3
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.py
file.
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 models
in Blog
the class, then by adding a new blog_list
function that returns JsonResponse
the 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_website
the folder in urls.py
the 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.py
the file appears twice.
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/admin
access before the blog background involved input http://127.0.0.1:8000/blog/list/
to get the data in JSON format.
The data in JSON format is as follows. Chinese has been UNICODE encoded and
can also be queried directly through the developer tools, just click on the blue rectangular area in the figure below.
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.py
configuration, 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.urls
the 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_list
function, which is used to return JSON-formatted data. Note blog_view
is imported view
modules 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.py
file.
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_time
after, pay attention to the following command sqlite
to 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 blog
folder urls.py
file, 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/1
be 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_id
acquired, but blog_id
will be passed to the detail
method.
The code there is a special need to explain <int:blog_id>
the foregoing int
is 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_list
method to expand, let it implement paging operation. Focus on views.py
the 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 Paginator
paging 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=1
resulting effect is as follows:
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
- 100 Python crawler tutorials, great crawler tutorials, subscribe now
- Python game world (updated, the target number of articles is 50+, subscribe now, all are old fans)
- Python crawler lesson, 9 wonderful lectures
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 pdfToday 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 .