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

Time:2022-5-7

Eraser, a funny senior Internet bug. New series, let’s enter the Django world together.

Completed articles

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.pyDocuments.

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 filemodelsMediumBlogClass, and then add a newblog_listFunction returnJsonResponseObject.

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_websiteIn folderurls.pyThe 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.pyThe file appears twice.

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

20210329091911450[1].png

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/adminvisitPrevious blogBackground involved, inputhttp://127.0.0.1:8000/blog/list/Get the data in JSON format.

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

20210329092108712[1].png

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

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

20210329092306460[1].png

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

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

20210329092456588[1].png

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.pyConfiguration in, i.e. the following code:

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

Found matches in URLblog/, and then loadblog.urlsFile, 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_listFunction, which is used to return data in JSON format. be carefulblog_viewIs importedviewThe 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.pyDocuments.

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_timeAfter that, pay attention to the following commandssqliteRegenerate.

> 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 modifyblogIn folderurls.pyFile, 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/1Obtain 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_idGet, andblog_idWill be passed todetailMethod.

There is another need to explain the above code<int:blog_id>aheadintIt 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;
  • pathMatch 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_listMethod to implement paging operation. Focus onviews.pyMediumblog_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 PaginatorThe 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=1The results are as follows:

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

20210329175424822[1].png

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

  1. Python crawler 100 case tutorial, great crawler tutorial, subscribe now
  2. Python game world (in the update, the number of target articles is 50 +, now subscribe, all old fans)
  3. 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>

Recommended Today

Huawei folding screen adaptation

Huawei folding screen adaptation scheme: Huawei has a system level support scheme for large screen equipment. Huawei has a parallel view and can support folding screen split screen display Huawei folding screen split screen display effect Screenshot_20210527_160252_com.tencent.mm.jpg Introduction to Huawei parallel visionParallel horizon is a technology to display applications on large screen devices such as […]