django piecemeal attention to points

app must first go to the newly created registered settings.py

INSTALLED_APPS = [
                'django.contrib.admin',
                'django.contrib.auth',
                'django.contrib.contenttypes',
                'django.contrib.sessions',
                'django.contrib.messages',
                'django.contrib.staticfiles',
                # 'app01'  # 简写
                'app01.apps.App01Config'  # 全称
            ]

html files all on the default templates folder

For the preceding paragraph has been written document we just use it to take over these files can be called "static files"

Static files can be:

  Bootstrap preceding frame it has been written for a class of

  image

  css

  js

Static files all on static default folder

  static default folder subfolders folder will be created by default

    css folder of the current web site style files

    js file js file all current site

    img file current site all picture files

    Other (front-end framework code third-party plug-in code ...)

Note: django project started when we must make sure that a port number is only a django project would be likely to result in otherwise occupied bug

 

Users can access all resources in the url

Only relevant resources url in the open you can access the (******)

 

Back-end resources generally need to manually specify whether exposed to the user

Static configuration file

STATICFILES_DIRS = [
         os.path.join(BASE_DIR,'static'
]

You just enter a specific path of the folder can access to static files

= STATIC_URL ' / static / '   # the name of the folder is not a static but rather an interface prefix 
    "" " as long as you want access to a resource file path to a static file must start with a static " "" 
    # manually static folder all exposed to the user resources 
    STATICFILES_DIRS = [ 
        os.path.join (base_dir, ' static ' ),   # real folder path 
        os.path.join (base_dir, ' static1 ' ),   # real folder path 
        os.path.join (base_dir, ' static2 ' ),   # the real folder path 
        os.path.join (base_dir, ' static3 ')  #The real folder path 
    ]

The default is to support automatic restart django code so only need to refresh the page several times on it

But sometimes it's slow restart mechanism

  Mechanism: real-time monitoring file changes as long as the code changes will automatically restart

  Your code may have not finished this time will automatically error

Static file interface prefix "dynamic analysis"

Load static%}% { 

        < Link the rel = "this stylesheet" the href = "{% static 'on Bootstrap-3.3.7-dist / CSS / bootstrap.min.css'}%" > 
        < Script the src = "{% static' on Bootstrap dist--3.3.7 / JS / bootstrap.min.js'}% " > </ Script > 
    using parser dynamically obtaining interface prefix

The default is to get a request form form

  Way to say hello to carry data is the url followed by data

  http://127.0.0.1:8000/login/?username=zekai&password=123

  It can be changed by a post request method

  After post requests need to go into your settings file comment out a middleware

MIDDLEWARE = [
            'django.middleware.security.SecurityMiddleware',
            'django.contrib.sessions.middleware.SessionMiddleware',
            'django.middleware.common.CommonMiddleware',
            # 'django.middleware.csrf.CsrfViewMiddleware',
            'django.contrib.auth.middleware.AuthenticationMiddleware',
            'django.contrib.messages.middleware.MessageMiddleware',
            'django.middleware.clickjacking.XFrameOptionsMiddleware',
        ]

Submit the form data form the destination by the action

  Default submission to the current address under 1. do not write

  2. You can also write suffix / index /

  3. You can also write the full path

General view of the main function will first get request processing

DEF Login (Request):
             # view function for a different request should have different processing logic 
            # IF request.method == 'the GET': 
            #      Print ( 'received') 
            #      Print (request.method) can acquire distal # request manner and the whole string to uppercase 
            #      Print (type (request.method)) 
            #      return the render (request, 'the login.html') 
            # elif request.method == 'the POST': 
            #      # get user input accordingly Analyzing logic 
            #      return the HttpResponse ( "get brother") 
            IF request.method == ' the POST ' :
                 return the HttpResponse ( ' coming baby ' )
             return render(request,'login.html')

Front-end data acquisition

  Method acquisition request request.method

  Processing of the data is not just only wsgiref django backend module also done a lot of data processing

  GET

    request.GET data acquisition front-end get submitted (it is like a big dictionary)

    Value:  

      request.GET.get ( 'username')    # Although the default value is a list, but just take a list of the last element

      Strongly recommended form of use values ​​in brackets

      If you want to list all direct out (******)

      request.GET.getlist('hobby')

  POST

    request.POST data acquisition front-end post submission (it is like a big dictionary)

    Value:  

      request.POST.get ( 'username') # Although the default value is a list, but just take a list of the last element

      Strongly recommended form of use values ​​in brackets

      If you want to list all direct out (******)

      request.POST.getlist('hobby')

 

django default using built-in sqlite database

If you want it to another database needs to be configured in the configuration file settings

1.settings configuration file

DATABASES = {
            'default': {
                'ENGINE': 'django.db.backends.mysql',
                'NAME': 'day1',
                'HOST':'127.0.0.1',
                'PORT':3306,
                'USER':'root',
                'PASSWORD':'1',
                'CHARSET':'utf8'
            }

2.'ll tell init file in the project name or the name of the application init file django Do not use the default connection mysql mysqldb but the use of pymysql

import pymysql
pymsql.install_as_MySQLdb()

 

 

django orm

ORM Object Relational Mapping

  Class table

  Object a record

  Attribute value of the object field corresponding to

 

First need to write a model class in models.py under application

class User (models.Model):
     # the id field to the User table primary key fields in django orm you can not write to the master key django dictionary will default to your table to create a primary key field named id 
            # id = models.AutoField ( primary_key = True) # Once you specify the primary key field that will not be django will help you automatically create a 
            username = models.CharField (max_length = 32)   # username VARCHAR (32) CharField max_length parameters must be specified 
            password = models.IntegerField ()   # password int

************************************** need to perform database migration (synchronous) command **** ********************************

manage.py makemigrations python3    # only in (migrations folder) and modify the database records are not directly manipulate data 
python3 manage.py the migrate   # will modify the database record actually synchronized to the database 
Note: As long as the models move with database-related code it is necessary to re-execute the above two commands are indispensable (*****)

 

Field of deletions change search

  increase

    When a table has been created out of the follow-up would also like to add a field, there are two ways

      1. When the new field to the default value

        addr = models.CharField(max_length=32,default='China')

      2. Give the new field to be empty

        age = models.IntegerField (null = True) # This field can be empty

  Deleted (caution)

    Delete the comment field directly in the field models.py and then re-execute two commands to

    Note: delete all the data in the table corresponding to all of the fields after performing

    And under normal circumstances it is basically will not be used to delete the true sense

 

orm operation requires the use of models in the name of the class

  Check data

    from app01 import models

    models.User.objects.all () # get all the data directly

    models.User.objects.get(username=username)

  # 1.1 GET () 
        # USER_OBJ = models.User.objects.get (username = username) from User # SELECT * WHERE username = 'Jason' 
        # "" " 
        # GET method can directly get the data object itself but when the query conditions are not when there is an error directly is not recommended for all 
        # "" " 
        # Print (USER_OBJ) 
        # Print (user_obj.username) 
        # Print (user_obj.password)

    res =  models.User.objects.filter(username=username)

    res.query

    user_obj = res.first()

# 1.2 filter () 
        # RES = models.User.objects.filter (username = username, password = password) 
        "" " 
        filter out the query result is a" place of the list is the one in the list of data object itself " 
        when the query does not exist when the error will not only return an empty list of 
        relationship between support to write multiple parameters and parameters and parameter and filter within brackets 
        "" " 
        # Print (res.query) # only querySet objects can be directly Check point query inside of the corresponding sql statement 
        # results 1.filter get is a querySet objects (you now only need to know the results of the filter will be able to get the point of view sql query statement) 
        "" " 
        the SELECT` app01_user`.`id `,` app01_user`.`username`, `app01_user`.`password` 
        the FROM` app01_user` 
        the WHERE ( `` app01_user`.`password` the AND app01_user`.`username` = Jason = 123) 
        
        "" "
        # print(res)
        # user_obj = res[0:2]
        "" " 
        QuerySet objects you can now use it as a list of actions by the index value can be taken (querySet only support a positive number does not support negative indexes) also support slicing (cut out the result was a querySet objects) 
        but do not recommend you do that 
        "" " 
        USER_OBJ = models.User.objects.filter (username = username) .first ()   # get the list of the first data object 
        " "" 
        not recommended that you use an index value because once without any data re-index values will complain 
        but if the interior is also in accordance with the first although the index value but no data no error will be returned None 
        "" " 
        # Print (USER_OBJ, user_obj.username, user_obj.password)

  Increased data

    1.

    models.User.objects.create(username=username,password=password)

# 1.Create () 
        # RES models.User.objects.create = (username = username, password = password) INSERT INTO User # (username, password) values (username, password) 
        # "" " 
        # Create new method can data and has a return value 
        # return value is the new data object itself 
        # "" " 
        # Print (RES) 
        # Print (res.username) 
        # Print (res.password)

 

    2. Using Objects

    user_obj = models.User(username=username,password=password)

    user_obj.save()

  Delete data

    models.User.objects.filter(条件).delete()

DEF del_user (Request):
     # Take deleting database data according to user wants to delete the id value of data 
    # acquired id value 
    delete_id = request.GET.get ( ' id ' )
     # Delete database to id holding 
    models.User .objects.filter (ID = delete_id) .Delete ()   # Delete User from WHERE ID = delete_id; 
    return the redirect ( ' / UserList / ' )

 

  Change data

    models.User.objects.filter(条件).update()

DEF update_user (Request):
     # editor is based on a modification of the existing data 
    # logic: Obtaining primary key values of data the user wants to modify the database and to modify the data 
    edit_id = request.GET.get ( ' ID ' )
     # check out the user data to show to let the user modify the page 
    edit_obj = models.User.objects.filter (the above mentioned id = edit_id) .first ()
     # pass the object to the front page editor 

    IF request.method == ' POST ' :
         # Do not post requests in relation thinking also get request parameters get carried 
        username = request.POST.get ( ' username ' ) 
        password = request.POST.get ( ' password ')
         # Update data 
        # mode. 1: 
        # models.User.objects.filter (ID = edit_id) .Update (username = username, password = password) 
        # Update User SET username = username, password = WHERE ID = edit_id password 
        "" " 
        filter to get a list of filter operations are actually batch operations 
        if there is more data then all at once will result in modifying filter list 
        is similar to a loop for a modify 
        
        "" " 
        # Second way (not recommended) 
        edit_obj.username = username 
        edit_obj.password = password 
        edit_obj.save () 
        "" " 
        the second way would start to finish all the fields of all changes again extremely inefficient 
        " "" 
        return redirect ( '/userlist/')
    return render(request,'update_user.html',{"edit_obj":edit_obj})

 

Guess you like

Origin www.cnblogs.com/KrisYzy/p/11529871.html