Django learning record

Posted by sgalatas on Wed, 05 Jan 2022 08:01:48 +0100

Django development

Install django

Install django: pip3 install django==2.2.12

Check the django version installed: python -m django --version

  1. Create project

    django-amdin startproject mysite

  2. Start service

    1. Enter project folder

    2,python3 manage.py runserver

  3. Change port number

    python manage.py runserver port number

Project structure

  • manage.py: a command line tool that allows you to manage Django projects in various ways

    • runserver: start service
    • startapp: create application
    • migrate: database migration
    • python3 manage.py: view all commands
  • The mysite / directory on the inner layer contains your project, which is a pure Python package. Its name is the python package name you need to use when you reference anything inside it. (e.g. mysite.urls)

  • mysite/__init__.py: an empty file that tells Python that this directory should be considered a Python package.

  • mysite/settings.py: configuration file of Django project.

    Public configuration, custom configuration

    import os
    
    
    Project absolute path
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    
    
    Project startup mode
    DEBUG = True
    true Debug mode
    false Online mode
    
    
    Filter request header Host head
    ALLOWED_HOSTS = []
    
    
    # Application definition
    
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
    ]
    
    
    middleware 
    MIDDLEWARE = [
    
    ]
    
    
    
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        }
    }
    
    
    
    Page display language
    zh-hans
    LANGUAGE_CODE = 'en-us'
    
    
    time zone
    Asia/Shanghai
    TIME_ZONE = 'UTC'
    
    USE_I18N = True
    
    USE_L10N = True
    
    USE_TZ = True
    
    
    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/2.2/howto/static-files/
    
    STATIC_URL = '/static/'
    
  • mysite/urls.py: the URL declaration of Django project, just like the "directory" of your website.

  • mysite/wsgi.py: as the portal for your project running on a WSGI compatible Web server.

URL and view functions

  • Sample

    #file: < under the folder with the same name as the project > / views py
    from django.http import HttpResponse
    
    def page1_view(request):
      html = "<h1>This is the first page<h1>"
      return HttpResponse(html)
    
    Simultaneous configuration url file 
    add to path route
    

Routing configuration

  • Sample

    setting.py In file root_urlconf Primary routing configuration list is specified urlpatterns File location for
    
    
    path function
     Import - from django.urls import path
     grammar - path(route,views,name-None)
    Parameters:
    1,route: String type, matching request path
    2,views: Specifies the name of the view handler function corresponding to the path
    3,name: It is an address alias, which is used in reverse address resolution in the template
    
  • path converter

    Syntax:<Converter type: custom name>
    Function: if the converter type matches the data of the corresponding type, the data will be passed to the view function by keyword parameter transfer
    
    example: path('page/<int:page>',views.xxx)
    
  • re_path() function

    Regular expressions can be used for exact matching during URL matching

Request and response

Request refers to the data sent by the browser to the server through HTTP protocol

  • path_info: url string

  • Method: a string representing the HTTP request method. Common values are "GET" and "POST"

  • Get: the object of QUeryDict query dictionary, which contains all data of get request mode

  • Post: the object of QUeryDict query dictionary, which contains all data of post request mode

  • FILES: a dictionary like object that contains all uploaded file information

  • Cookies: a python dictionary that contains all cookies. The keys and values are strings

  • Session: a dictionary like object that represents the current session

  • Body: string, the content of the request body

  • scheme:

  • request.get_full_path():

  • Request.META: metadata in request (message header)

Response refers to the data that the server does corresponding processing after receiving the request and replies to the browser

  • Response status code
    • 200: request succeeded
    • 301: permanent redirection - resources (web pages, etc.) are permanently transferred to other URL s
    • 302: temporary redirection
    • 404: the requested resource (web page, etc.) does not exist
    • 500: internal server error
  • django response object

POST and GET requests

  • processing logic

    if request.requestmethod == 'GET':
      handle GET request
    else request.method == 'POST':
      handle POST request
    else:
      Other requests
    
  • Error 403 is reported, and csrf verification is cancelled

    Disable setting middleware of CrfsViewsMiddleWare in PY

Django design pattern and template layer

  1. Design pattern

    MTV

  2. Template layer

    What is a template?
    1. It is an html web page that can change dynamically according to dictionary data
    2. The corresponding html web pages can be generated dynamically according to the dictionary data transmitted in the view
    Template configuration
    • Create template folder < project name > / template
    • In settings templates configuration item in PY
      1. BACKEND: engine for making templates
      2. DIRS: the search directory of the template only needs to be modified (set DIRS - 'DIRS': [os.path.join(BASE_DIR,'templates'),)
      3. APP_DIRS: do you want to search for template files in the template folder in the app
      4. OPTIONS: OPTIONS for templates
    Loading method of template
    • Obtain the template through the loader and respond through HttpResponse

      1. In the views file

        def test_html(request):
        	from django.temlates import loader
        	t = loader.get_template("Template file name")
        	html = t.render(Dictionary data)  //Convert to string
        	return HttpResponse(html)
        
      2. Create a file in the templates folder

      3. In URLs Add path to py file

    • Use render() to load and respond directly to the template

      1. In view function

        from django.shortcuts import render
        return return(request,'Template name',Dictionary data)
        
    Interaction between view layer and template layer
    1. In the view function, python variables can be encapsulated in the dictionary and passed to the template layer

      def xx_view(request):
        dic = {
          "Variable 1":"Value 1",
          "Variable 2":"Value 2",
        }
        return render(request,'xx.html',dic)
      
    2. In the template, the syntax of {{variable name}} can be used to call the view to pass in

    Template layer variables and labels
    1. Template layer variable

      • Data types that can be passed to the template
        • str - string
        • list - array
        • dict - Dictionary
        • obj - class instantiation object
        • int - integer
        • Tuple - tuple
        • func - Method
      • Using variable syntax in templates
        • {{variable name}}
        • {{variable name. index}}
        • {{variable name. key}}
        • {{object. Method}}
        • {{function name}}
    2. Template label

      Tag syntax

      {% label %}
      ...
      {% End tag %}
      
    Template layer - filters and inheritance
    • filter

    • inherit

      1. In parent template

        • Defines the block label in the parent template
        • It indicates that the rest in the sub module is allowed to be modified
        • block tag: defined in the parent module and can be overwritten in the child module
      2. In sub module

        • Inherit the template extensions tag (written on the first line of the template file)

          {%extends 'base.html'%}
          
        • The child template overrides the content module in the parent module

          {% block block_name%}
          The child template is used to overwrite the parent template block_name Block content
          {% endblock block_name %}
          

URL reverse parsing

url reverse parsing refers to dynamically finding or calculating the corresponding route with the name defined by path in the view or template

Syntax of the path function

path(route,views,name = "alias")

path('page',views.page_view,name="page_url")

According to the 'name =' keyword in the path, a unique name is determined for the url. In the template or view, the url information can be inferred inversely from this name

In the template - the reverse resolution of the address is realized through the url tag

{% url  'alias' %}

{% url 'alias' 'Parameter value 1' 'Parameter value 2' %}

ex:
{% url 'pagen' '400' %}
{% url 'person' age='18' name='gxn' %}

In the view function - > you can call the reverse method in django for reverse parsing

from django.urls import reverse
reverse('alias',args=[],kwargs={})

Static file

Static file configuration - settings In PY

  1. Configure static file access path

    • Which url address to use to find the static file

    • static_url = '/static/'

    • explain

      Specify that / static / xxx or http://127.0.0.1:8000/static/xxx[xxx indicates the specific file location]

  2. Configure the storage path of static files STATICFILES_DIRS

    It saves the storage location of static files on the server side

    STATICFILES_DIRS= (
    	os.path.join(BASE_DIR,"static"),
    	)
    
  3. Accessing static files in templates - img tags as an example for more dynamic writing

    Access static files through the {% static%} tag

    • Load static - {% load static%}

    • Use static resources -- {% static 'static resource path'%}

    • Sample

      <img src="{% static 'image/lena.jpg' %}">
      

Django applications and distributed routing

application

Application is an independent business module in django project, which can contain its own routing, view, template and model

Create application

  1. Use manage The subcommand startapp in py creates an application folder

    python3 manage.py startapp music
    
  2. In settings Py installed_ Configure and install this app in the apps list

Distributed routing

In Django, the main route configuration file (urls.py) can not handle user specific routes, and the main route configuration file can distribute requests (distributed request processing) Specific requests can be processed by their respective applications

  1. Calling include function in main routing

    Syntax: include('app name. url module name ')

    Function: it is used to transfer the current route to the urlpatterns of the routing configuration file of each application for distributed processing

    path('music/',include('music.urls'))
    
  2. Configure URLs under application py

    Manually create URLs under application py

    The content structure is exactly the same as the main route

Model layer and ORM

Model layer - responsible for communication with the database

Django configuring mysql

Install mysqlclient

Topics: Django