Eraser, a funny senior Internet bug. New series, let’s enter the Django world together.
Completed articles
- Snowball learning Python third round, the world of Django in Python Web
- With a little hand shaking, you can implement a micro blog system with Python Django
- Django is a small backstage, and the details are improving a little. Snowball learns the third stage of Python
- Django queryset just learn a little, a little is enough
5、 Python Django view
5.1 JSON data returned from view
In real work, python web engineers will feed back interface data to front-end engineers. The interface is generally called API. The common format of returned data is XML or JSON. Next, take the most common JSON format data as an example to explain in detail how Django sends data from the database to the front-end.
modifyviews.py
Documents.
from django.shortcuts import render
#Import JSON format data response class
from django.http import JsonResponse
from .models import Blog
# Create your views here.
def blog_list(request):
blogs = Blog.objects.all()
#Generate an object with list generator
context = {
"data": [{"id": blog.id, "title": blog.title} for blog in blogs]
}
return JsonResponse(context)
Import in the header of this filemodels
MediumBlog
Class, and then add a newblog_list
Function returnJsonResponse
Object.
5.2 creating routes
Routing related information will be supplemented later. This blog only needs to know that different data can be returned through different URLs.
Create a new file in the blog folderurls.py
, the code is as follows:
from django.urls import path
import blog.views as blog_views
urlpatterns = [
path('list/', blog_views.blog_list)
]
The code of the file is written and needs to be modifiedmy_website
In folderurls.py
The document is amended as follows:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('blog/', include('blog.urls')),
path('admin/', admin.site.urls),
]
At this time, your project file structure is shown in the figure below. Pay attention to iturls.py
The file appears twice.

Run the current application with the following command:
python manage.py runserver
Direct accesshttp://127.0.0.1:8000/
The following error occurs, requiring access to a directory. inputhttp://127.0.0.1:8000/admin
visitPrevious blogBackground involved, inputhttp://127.0.0.1:8000/blog/list/
Get the data in JSON format.

The data in JSON format is as follows, and Chinese is encoded in Unicode

Similarly, you can query directly through the developer tool and click the blue rectangular area in the figure below.

After the application is completed, you can repeat the disk learning.
Access through URL address, if the access address is/blog
, Django will load automaticallyurls.py
Configuration in, i.e. the following code:
urlpatterns = [
path('blog/', include('blog.urls')),
path('admin/', admin.site.urls),
]
Found matches in URLblog/
, and then loadblog.urls
File, the corresponding file code is as follows:
from django.urls import path
import blog.views as blog_views
urlpatterns = [
path('list/', blog_views.blog_list)
]
This includes alist/
Matcher, so passblog/list/
Called in viewblog_view.blog_list
Function, which is used to return data in JSON format. be carefulblog_view
Is importedview
The module is renamed, and the code is in the headerimport blog.views as blog_views
。
def blog_list(request):
blogs = Blog.objects.all()
#Generate an object with list generator
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 detail page
With the above logical relationship, after implementing an interface to return a single blog data, edit it firstviews.py
Documents.
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)
Expand the details page, find a word spelling error, modify itcreate_time
After that, pay attention to the following commandssqlite
Regenerate.
> 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> 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
02_auto_20210329_0940.py
- Rename field creatr_time on blog to create_time
After the command is run, 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 modifyblog
In folderurls.py
File, code 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 writing the above code, you can passhttp://127.0.0.1:8000/blog/detail/1
Obtain a single blog data, and the format of address URL ishttp://127.0.0.1:8000/blog/detail/ {integer sequence number}
。
Enter the integer serial number in the address, which can be used by the backgroundblog_id
Get, andblog_id
Will be passed todetail
Method.
There is another need to explain the above code<int:blog_id>
aheadint
It is called path converter. Common path converters include the following:
-
str
: matches any non empty string, default value; -
int
: match zero or positive integer; -
uuid
: match a specific type of string format; -
path
Match any non null character, and you can match the path address, including:/
。
The following blogs will cover the above contents. First, apply them. After all, the snowball series is a column for repeated learning.
5.4 paging implementation
Next, continue toblog_list
Method to implement paging operation. Focus onviews.py
Mediumblog_list(request)
The core code refers to the following contents.
from django.shortcuts import render
#Import JSON format data response class
from django.http import JsonResponse
#Import paging components
from django.core.paginator import Paginator
from .models import Blog
# Create your views here.
def blog_list(request):
# blogs = Blog.objects.all()
## generate an object with the list generator
# context = {
# "data": [{"id": blog.id, "title": blog.title} for blog in blogs]
# }
#Page number: get the page parameter by default, and the default value is 1
page = request.GET.get("page", 1)
#20 pieces of data per page by default
page_size = request.GET.get("page_size", 20)
#Get all data
blog_all = Blog.objects.all()
#Paging object
paginator = Paginator(blog_all, page_size)
#Current page number
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)
Import at the top of the codefrom django.core.paginator import Paginator
The paging module is used for subsequent paging contents, and the data passes throughBlog.objects.all()
The method is obtained in advance. This method has efficiency problems. This part will be modified after learning the advanced content.
After writing, the paging effect can be realized through URL related parameters. visithttp://127.0.0.1:8000/blog/list/?page=1&page_size=1
The results are as follows:

5.5 summary of this blog
This blog focuses on the view in Django. This paper is based on function view (FBV). In future blogs, we will learn class based view (CBV). Class based view is widely used in practical development. There is also a mature framework for reference when using Django development API, such asDjango Rest Framework
。
Related reading
- Python crawler 100 case tutorial, great crawler tutorial, subscribe now
- Python game world (in the update, the number of target articles is 50 +, now subscribe, all old fans)
- Python crawler class, wonderful 9 lectures
Today is the < font color = “red” > 122 < / font > / 200th day of continuous writing.
If you want to establish an intimate relationship with bloggers, you can follow the official account of the same name <font color= “red” > dream eraser </font> and get in close touch with a funny senior Internet worm.
Blogger ID: Dream eraser. I hope you < font color = “red” > like < / font >, < font color = “red” > comment < / font >, < font color = “red” > collection < / font >.
<font color=white size=1>
Django wechat applet mall Django tutorial 2020 PHP cool
Django and spring compare Django open source projects why do large companies rarely use Vue
Python Django framework how to install Django enterprise development practice pdf
</font>