"Django Web Framework Notes 1"

"Django Web Framework Notes 1"

table of Contents


  • Course features:
    1. Difficult to learn, most of the content needs to be understood and memorized
    2. More files are confusing
    3. Focus on the use of the framework during the learning phase, and focus on the realization of business logic during the work phase
    4. Strong comprehensive application, few small exercises

Introduction to Django framework

  • Released in 2005, an open source web framework written in Python

  • In the early days, Django was mainly responsible for news and content management

  • A heavyweight Python web framework, Django is equipped with most of the commonly used components

    1. basic configuration
    2. Routing system
    3. Native HTML template system
    4. View
    5. Model, database connection and ORM database management
    6. Middleware
    7. Cookie & Seesion
    8. Pagination
    9. Database background management system admin
  • The purpose of Django

    • Website back-end development
    • WeChat official account, WeChat applet and other background development
    • Development of background server based on HTTP/HTTPS protocol
    • tornado/gevent 4th floor
      • Online voice/image recognition server
      • Online third-party authentication server, etc.
  • Django version

    • Latest version: 2.2.x
    • Current teaching version: 1.11.8
  • Django's official website

Django installation

  • View installed version

    >>> import django >>> print (django.VERSION) ( . 1 , . 11 , . 8 , 'Final' , 0 ) copying the code
  • installation

    1. Online installation
      • $ sudo pip3 install django
        Install the latest version of django
      • or
      • $ sudo pip3 install django[==version]
        Install the specified version of django
      • Such as:
        • $ sudo pip3 install django==1.11.8
    2. Offline installation
      • Download the installation package:
      • Install offline package
        • $ tar -xvf Django-1.11.8.tar.gz
        • $ cd Django-1.11.8
        • $ sudo python3 setup.py install
    3. Install offline with wheel
      • Download the installation package:
        • pip3 download -d/home/tarena/django_packs django==1.11.8
      • Install offline package
        • $ pip3 install Django-1.11.8.whl
  • Django uninstall

  • $ pip3 uninstall django

  • Django development environment

    • Django 1.11.x supports Python 2.7, 3.4, 3.5 and 3.6 (long-term support version LTS)
    • Note: Django 1.11.x does not support Python 3.7

Django framework development

Instructions for creating a project

  • $ django-admin startproject project name

  • Such as:

    • $ django-admin startproject mysite1
  • run

    $ Cd mysite1 $ python3 manage.py the runserver # or $ python3 manage.py the runserver 5000 # specify only the machine to access the machine using port 5000 of copy the code

The directory structure of the Django project

  • Example:

    $ django-admin startproject mysite1 $ tree mysite1/ mysite1/ manage.py mysite1 __init__.py settings.py urls.py wsgi.py 1 directory, 5 files Copy code
  • Analysis of project directory structure:

    • manage.py
      • This file is the main program of project management, which is used to manage the development and operation of the entire project during the development phase.
      • manage.py
        Contains subcommands for project management, such as:
        • python3 manage.py runserver
          Start service
        • python3 manage.py startapp
          Create application
        • python3 manage.py migrate
          Database migration
        • ...
    • mysite1 project package folder
      • The main folder of the project package (the default is the same as the project name)
      1. __init__.py

        • Package initialization file, this file will run automatically when the project package is imported (import)
      2. wsgi.py

        • WSGI is Web Server Gateway Interface connected with nginx
        • The configuration file of the WEB service gateway interface, only used when deploying the project
      3. urls.py

        • The basic routing configuration file of the project, all dynamic paths must go through this file to match
      4. settings.py

        • The configuration file of the Django project, some global variables in this configuration file will pass some parameters for the running of the Django framework
        • setting.py configuration file, automatically invoked when the service is started,
        • Some custom variables can also be defined in this configuration file for data transfer in the global scope

  • settings.py
    File introduction

    1. BASE_DIR

      • Absolute path used to bind the current project (dynamically calculated), all files can follow this path
    2. DEBUG

      • Used to configure the enable mode of the Django project, the value is:
        1. True means used in the development environment
          Debug mode
          (Used in development)
        2. False means that the current project is running
          In the production environment
          (Do not enable debugging)

      • Set the list of network addresses allowed to access this project, value:
        1. [] Empty list, means only

          Can access this project
        2. ['*'], which means that any network address can access the current project
        3. ['', ''] means that only the current two hosts can access the current project
        • note:
          • If you want to access this host from other hosts on the LAN, the startup method should use the following mode:
      • python3 manage.py runserver
        # Specify that all hosts of the network device can be accessed through port 5000 (need to add
        ALLOWED_HOSTS = ['*']

      • Specify the list of apps installed in the current project

      • Used to register middleware

      • Configuration information used to specify the template

      • Used to specify the configuration information of the database

      • Used to specify language configuration
      • Value:
        • English:
        • Chinese:
    9. TIME_ZONE

      • Used to specify the current server-side time zone
      • Value:
        • UTC:
        • China time zone:

      • Used to configure the root-level url configuration'mysite1.urls'
      • Such as:
        • ROOT_URLCONF ='mysite1.urls'

    Note: This module can pass

    from django.conf import settings
    Import and use

URL introduction

  • url is Uniform Resource Locator

  • effect:

    • Used to represent the address of a resource on the Internet.
  • Description:

    • Every file on the Internet has a unique URL, which contains information that indicates the location of the file and how the browser should handle it.
  • The general syntax format of URL is:

  • www.djangoproject.com/download/

    protocol://hostname [: port] [? query]/path [# fragment] Copy the code
  • Such as:

    http://tts.tmooc.cn/video/showVideo?meuId=657421&version=AID201908#sCopy code
  • Description:

    • protocol
      • http Access this resource via HTTP. format
      • https access this resource via secure HTTPS. format
      • The file resource is a file on the local computer. format:
      • ...
    • hostname
      • Refers to the Domain Name System (DNS) host name, domain name, or IP address of the server that stores the resource.
    • port (port number)
      • Integer, optional, use the default port of the scheme when omitted;
      • Various transmission protocols have default port numbers. For example, the default port of http is 80. HTTPS 443
    • path (routing address)
      • A character string separated by zero or more "/" symbols is generally used to represent a directory or file address on the host. The routing address determines how the server handles this request
    • query
      • Optional. It is used to pass parameters to the dynamic web page. There can be multiple parameters, separated by "&" symbols, and the name and value of each parameter are separated by "=" symbols.
    • fragment (information fragment)
      • String, used to specify the segment in the network resource. For example, if there are multiple noun explanations in a webpage, you can use fragment to directly locate a noun explanation.
    • Note: [] means that the content can be omitted

View function (view)

  • The view function is a function used to receive a browser request and return data through the HttpResponse object. This function can receive the browser request and return the corresponding content to the browser according to the business logic

  • The syntax format of the function processed by the view:

    DEF xxx_view ( Request [, other parameters ...] ): return the HttpResponse objects duplicated code
  • parameter:

    • request is used to bind the HttpRequest object, through which the parameters and data of the browser can be obtained
  • Example:

    • View processing function
      # File: <project name>/views.py from django.http Import HttpResponse DEF page1_view ( Request ): HTML = "<h1> This is the first one page </h1>" return HttpResponse (HTML) Copy the code

Routing configuration in Django

  • in settings.py
    Specifies the file location of the main route configuration list urlpatterns
  • urls.py main routing configuration file
    # file: <project name>/urls.py urlpatterns = [ url( r'^admin/' , admin.site.urls), ... # Configure the main route here ] Copy code

    urlpatterns is a list of route-view function mapping, the mapping relationship of this list is determined by the url function

  1. url() function
    • Used to describe the correspondence between routing and view functions
    • Module
      • from django.conf.urls import url
    • syntax:
      • url(regex, views, name=None)
      • parameter:
        1. regex: string type, matching request path, regular expression allowed
        2. views: The name of the view processing function corresponding to the specified path
        3. name: alias the address, used in the template for reverse address resolution

    The r in front of each regular expression means

    Unescaped raw string

  • Exercise
    • Build a small website:

      Tip: The regularity of homepage routing is


      • Thinking
        • /page3/page4 ..../page100
        • What should I do if I create one hundred web pages as above?

Route and view functions with grouping

  • Within the view function, you can use regular expressions to group

    After extracting the parameters, use the function position to pass the parameters to the view function

  • One group represents one parameter, multiple parameters need to use multiple groups, and use/separate

  • Exercise:

    Input: Page display results: 300 Input: Page display result: -100 Input: Page display result: 20000 Copy code

Route and view functions with named groups

  • Named groups (capture groups) can be used in regular expressions of url

  • Description:

    • Within the view function, you can use regular expressions to group
      After extracting the parameters, use the function keyword to pass the parameters to the view function
  • Example:

    • Routing configuration file
      # file: <project name>/urls.py # The following example matches # # # urlpatterns = [ url( r'^admin/' , admin.site.urls), url( r'^person/(?P<name>\w+)/(?P<age>\d{1,2})' ,views.person_view), ] Copy code
  • Exercise:

  • PyCharm Community Edition debugging method for Django project

    1. Add your own tuning configuration
      • Select Add Configuration...
    2. Click on
      Add a configuration of your own
      • Select the main module location of the project to run manage.py
      • Add runserver command line parameters

HTTP protocol request and response

  • The request refers to the data sent by the browser to the server through the HTTP protocol
  • Response refers to the data that the server side receives the request and does the corresponding processing before replying to the browser side.

HTTP request

  • According to the HTTP standard, HTTP requests can use multiple request methods.

  • HTTP1.0 defines three request methods: GET, POST and HEAD methods (most commonly used)

  • HTTP1.1 adds five new request methods: OPTIONS, PUT, DELETE, TRACE and CONNECT methods.

  • HTTP 1.1 request details

    Serial numbermethoddescription
    1GETRequest the specified page information and return the entity body.
    2HEADSimilar to a get request, except that there is no specific content in the returned response, which is used to get the header
    3POSTSubmit data to the specified resource for processing request (such as submitting a form or uploading a file). The data is contained in the request body. POST requests may result in the creation of new resources and/or the modification of existing resources.
    4PUTThe data transmitted from the client to the server replaces the content of the specified document.
    5DELETERequest the server to delete the specified page.
    6CONNECTThe HTTP/1.1 protocol is reserved for proxy servers that can change the connection to the pipe mode.
    7OPTIONSAllow the client to view the performance of the server.
    8TRACEThe request received by the echo server is mainly used for testing or diagnosis.
  • HttpRequest object

    • The first parameter of the view function is the HttpRequest object
    • After the server receives the request of the http protocol, it will create an HttpRequest object according to the request data message
    • HttpRequest attributes
      • path: string, representing the requested routing information
      • path_info: URL string
      • method: string, indicating the HTTP request method, commonly used values:'GET','POST'
      • encoding: string, representing the encoding method of the submitted data
        • If it is None, it means to use the default setting of the browser, which is generally'utf-8'
        • This attribute is writable. You can modify the encoding used to access the form data by modifying it. Any subsequent access to the attribute will use the new encoding value
      • GET: QueryDict query dictionary object, including all data of get request method
      • POST: QueryDict query dictionary object, including all data of the post request method
      • FILES: An object similar to a dictionary, containing all uploaded file information
      • COOKIES: Python dictionary, contains all cookies, keys and values are strings
      • session: an object similar to a dictionary, representing the current session,
      • body: string, the content of the request body (POST or PUT)
      • environ: string, the environment variable information of the client running
      • scheme: Request protocol ('http'/'https')
      • request.get_full_path(): the full path of the request
      • request.get_host(): the requested host
      • request.META: the metadata in the request (message header)
        • request.META['REMOTE_ADDR']: client IP address

HTTP response

  • When a viewer visits a web page, the viewer's browser will send a request to the server where the web page is located. Before the browser receives and displays the webpage, the server where the webpage is located will return an information header containing the HTTP status code to respond to the browser's request.

  • The English of HTTP status code is HTTP Status Code.

  • The following are common HTTP status codes:

    • 200-request successful
    • 301-Resources (webpages, etc.) are permanently transferred to other URLs
    • 404-The requested resource (webpage, etc.) does not exist
    • 500-Internal server error
  • HTTP status code classification

    • The HTTP status code is composed of three decimal digits. The first decimal digit defines the type of the status code, and the latter two digits have no classification function. There are 5 types of HTTP status codes:

      classificationClassification description
      1**Information, the server receives the request and needs the requester to continue the operation
      2**Success, the operation was successfully received and processed
      3**Redirect, further action is required to complete the request
      4**Client error, the request contains a syntax error or the request cannot be completed
      5**Server error, the server encountered an error while processing the request
  • The response object HttpResponse in Django:

    • Constructor format:

      • HttpResponse(content=response body, content_type=response body data type, status=status code)
    • effect:

      • Return a response to the client browser and carry the content of the response body at the same time
    • parameter:

      • content: Indicates the content returned.
      • status_code: The returned HTTP response status code (the default is 200).
      • content_type: Specify the MIME type of the returned data (the default is "text/html"). The browser will display the data based on this attribute. If it is text/html, then the string will be parsed, if text/plain, then a plain text will be displayed.
        • The commonly used Content-Types are as follows:
          • 'text/html'
            (Default, html file)
          • 'text/plain'
            (Plain Text)
          • 'text/css'
            (Css file)
          • 'text/javascript'
            (Js file)
          • 'multipart/form-data'
            (File submission)
          • 'application/json'
            (Json transmission)
        • 'application/xml'
          (Xml file)

        Note: The keyword MIME (Multipurpose Internet Mail Extensions) refers to the type of multipurpose Internet mail extensions.

  • HttpResponse subclass

    Types ofeffectstatus code
    HttpResponseBadRequestBad request400
    HttpResponseNotFoundNo corresponding resources404
    HttpResponseForbiddenRequest is forbidden403
    HttpResponseServerErrorServer Error500

GET parameter transfer

  • In the GET request mode, data can be passed to the server through a query string

  • URL format:

    xxx? Parameter name 1=value 1 meter name 2=value 2...

    • Such as:
  • The server receives the parameters

    1. Judge the value of request.method Judge whether the request method is a get request
      if request.method == 'GET' : Business logic when processing GET requests else : Business logic for processing other requests Copy code
    2. Get the data submitted by the client request GET request
      1. syntax
        request.GET[ 'parameter name' ] # QueryDict request.GET.get( 'parameter name' , 'default value' ) request.GET.getlist( 'parameter name' ) # mypage?a=100&b=200&c=300&b=400 # request.GET=QueryDict({'a':['100'],'b':['200', '400'],'c':['300']}) # a = request.GET['a'] # b = request.GET['b'] # Error Copy code
      2. Where the get request method can be generated
        1. Enter the address bar manually, such as:
        2. <a href="address?parameter=value meter=value">
        3. The method in the form is get
          < form method = 'get' action = "/user/login" > Name: < input type = "text" name = "uname" > </form > Copy code

Generally, the size of the query string will be limited by the browser (it is not recommended to exceed 2048 bytes)

POST parameters

  • The client passes data to the server through POST requests such as forms, such as:
< form method = 'post' action = "/login" > Name: < input type = "text" name = "username" > < input type = 'submit' value = 'login' > </form > Copy code
  • The server receives the parameters

    • Use request.method to determine whether it is a POST request, such as:
    if request.method == 'POST' : Process POST request data and respond else : Handling of responses to non-POST requests Copy code
  • Use post to receive client data

    1. method
    request.POST[ 'parameter name' ] # request.POST binds QueryDict request.POST.get( 'parameter name' , '' ) request.POST.getlist ( 'Parameter name' ) copying the code
  • Cancel the csrf verification, otherwise Django will reject the POST request sent by the client

    • Cancel csrf verification

      • Delete the middleware of CsrfViewsMiddleWare in MIDDLEWARE in settings.py
      MIDDLEWARE = [ ... #'django.middleware.csrf.CsrfViewMiddleware', ... ] Copy code

form name attribute of the form

  • When the form control submits data, it will automatically search for the name attribute and the corresponding value of the subtag inside the form control, and then submit these names and values in the form of key-value pairs to the relevant server location specified by the action

  • The controls of the label of the name attribute that can be automatically collected in the form are:

    < INPUT name = 'XXX' > < SELECT name = 'yyy' > </SELECT > < TextArea name = 'ZZZ' > </TextArea > copy the code
    • Such as:
    < form action = "/page1" method = "POST" > < input name = "title" type = "text" value = "Please enter" > < select name = "gender" > < option value = 1 > Male </option > < option value = 0 > female </option > </select > < textarea name = "comment" rows = "5" cols = "10" > Postscript... </textarea > < input type = "submit" value = "Submit" > </form > Copy code