Django basics

First, install and use

  • Download and install

    • Command line: pip3 install django == 1.11.21

    • pycharm

  • Create a project

    • Command Line:

      • Find a folder to store the project file, open a terminal:

      • django-admin startproject Project Name

      • Project Directory

    • pycahrm

  • start up

    • Command Line

      • Switch to the root directory of the project under manage.py

      • python36 manage.py runserver —— 127.0.0.1:80`

      • python36 manage.py runserver 80——127.0.0.1:80

      • python36 manage.py runserver 0.0.0.0:80——0.0.0.0:80

    • pycharm: green triangle starting point can be configured

  • Simple to use

    • Example: Returns the specified HTML file

    # In urls.py the 
    # imported 
    from django.shortcuts Import the HttpResponse, the render 
    # function 
    DEF index (Request):
         # return the HttpResponse ( 'index') 
        return the render (Request, ' index.html ' ) 
    # URL and the corresponding function relationship between 
    the urlpatterns = [ 
        URL (R & lt ' ^ ADMIN / ' , admin.site.urls), 
        URL (R & lt ' ^ index / ' , index), 
    ] 

Second, static files

  • Configuration

    • Set in the settings.py

    = STATIC_URL ' / static / '           # Aliases 
    STATICFILES_DIRS = [             # Set the file path, can be provided a plurality of 
        the os.path.join (base_dir, ' static1 ' ), 
        the os.path.join (base_dir, ' static ' ), 
        the os.path .join (base_dir, ' static2 ' ), 
    ]  
  • use

    • Add an alias before the path: / static /

    • Multiple file paths, but also use the same alias, not the file name

    • If the path after the same alias name, in order to find a list of STATICFILES_DIRS

    < Link the rel = "this stylesheet" the href = "/ static / CSS / the login.css" >          {# #} beginning Aliases 

Third, the simple login example

  • form data form to submit questions to note:

    • Address filed: action = "", the requested mode: method = "post"

    • All attributes have a name input box, such as the name = "username"

    • There is a input box type = "submit" or there is a button

  • Submit post request, since Django has a csrf check, all requests will be problems

    • Solution: The settings in MIDDLEWARE of 'django.middleware.csrf.CsrfViewMiddleware' commented

  • Redirect

    • 导入:from django.shortcuts import redirect

    • Use

    # Used in the function, for example, 
    return the redirect ( ' / index / ' )       # Parameters: url Path 
    # Note: must be preceded by /, representatives from the root url splicing, or would have been spliced back current url
    from django.shortcuts Import the HttpResponse, the render, the redirect 
    DEF index (Request):
         # return the HttpResponse ( 'index') 
        return the render (Request, ' index.html ' ) 
    DEF Login (Request):
         IF request.method == ' POST ' :
             # acquire books form submitted form 
            username = request.POST [ ' username ' ] 
            password = request.POST [ ' password ' ]
             # authentication username and password 
            ifmodels.User.objects.filter (username = username, password = password):
                 # authentication is successful jump to the index page 
                # return the redirect ( 'https://www.baidu.com/') 
                return the redirect ( ' / index / ' )
             # unsuccessful login again 
        return the render (Request, ' the login.html ' ) 
    the urlpatterns = [ 
        URL (R & lt ' ^ ADMIN / ' , admin.site.urls), 
        URL (R & lt ' ^ index / ' , views.index) , 
        URL (R & lt ' ^ Login / ' , views.login), 
    ]
    Examples

Four, app

  • Creating app

    • Command line: python manage.py startapp app name

    • pycharm: tools -> run manage.py task -> enter the command: startapp app name

  • Register app

    • Settings.py provided in Example: app named app01

    = INSTALLED_APPS [ 
        ... 
        ' app01 ' ,
         ' app01.apps.App01Config ' ,        # recommended wording
  • app files

    • migrations: Migrating store file

    • admin.py:Django provides background management tool

    • app.py: information related to the app

    • models.py: ORM with related content

    • views.py: view, write function

Fifth, use the MySQL process

  • Create a MySQL database: create database day53;

  • In settings.py set, Django connect to the MySQL database:

    = DATABASES {
         ' default ' : {
             ' ENGINE ' : ' django.db.backends.mysql ' ,       # engine 
            ' NAME ' : ' day53 ' ,                          # database name 
            ' the HOST ' : ' 127.0.0.1 ' ,                      # IP address 
            ' PORT ' : 3306                             # port 
            ' the USER ' : 'the root ' ,                           # users 
            ' PASSWORD ' : ' 123 '                         # password 
        } 
    }
  • Written and settings, init py files in the same directory in which:

    import pymysql
    pymysql.install_as_MySQLdb()
  • Create a table (written under the app models.py class):

    from django.db import models
    ​
    class User(models.Model):
        username = models.CharField(max_length=32)       # username varchar(32)
        password = models.CharField(max_length=32)       # username varchar(32)
  • Run the database migration:

    • python manage.py makemigrations: model.py registered under detect each app, record changes of record model

    • python manage.py migrate: synchronized recording changes to the database

Six, MVC and MTV

  • MVC

    • M: model model - and interact with the database

    • V: view view - HTML

    • C: controller Controller - transfer instruction dispatch logic operations

  • MTV:

    • M: model model ORM - and interact with the database

    • T: tempalte Template - HTML

    • V: view view - business logic function

  • djando is MTV mode

Guess you like

Origin www.cnblogs.com/zengyi1995/p/11328946.html