Road Django learning 02

Static configuration file

html files all on the default templates folder

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

  • bootstrap preceding frame it has been written for a class of
  • image
  • css
  • js

By default, all static files in a folder under static, static folder by default will be created by default subfolders, CSS folder of the current site all the style files, js files current site all the js file, img file all the pictures of the current site documents, other (front-end framework code third-party plug-in code ...)

= 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 
]

ps: when looking for the path will be followed by a list of words to find all of the static files to find the path to stop immediately return a 404 not found

Because the interface prefix is ​​modified, then import the html file path should also be amended together, so the introduction of a static file interface prefix "dynamic analysis" This method:

# Static file interface prefix "dynamic resolution" 
    {% Load static% }

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

request method

request.method # acquisition request method 
# acquisition request to the way (all uppercase character string), such as 'the GET', 'the POST' 

# on the GET 
`` request.GET``   # retrieve a front get data submission (it is like a big Dictionary) 
request.GET.get ( ' username ' )   # Although the default value is a list, but just take a list of the last element 
# Note: You can also use the values in parentheses, but do not be so with 

# get all the elements in the list 
request.GET.getlist ( ' Hobby ' ) 


# About POST 
request.POST # get the front post data submitted (it is like a big dictionary) 

request.POST.get ( ' username ' ) # Although the value is a list of default but only take a list of the last element 
#Also not recommended to use the values in parentheses 

# for a full listing of 
request.POST.getlist ( ' Hobby ' )

About form form

" '" Form is the default form get request 
    way to say hello to carry data is the url followed by data 
    http://127.0.0.1:8000/login/?username=zekai&password=123 

    can be requested by post method instead 
. "" "

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

Submit the form data form the destination by the action

  1. The default submit to the current addresses without written
  2. You can also write suffix / index / (used this item)
  3. You can also write the full path
General view of the main function will first get a request handle
     DEF the Login (Request):
         # view function for different request should have different ways of processing logic 
        # IF request.method == 'GET': 
        #      Print ( 'received') 
        #      Print (request.method) # manner and capable of acquiring distal request string is all uppercase 
        #      Print (type (request.method)) 
        #      return the render (request, 'the login.html') 
        # elif request.method == 'the POST' : 
        #      # get user input logic is determined accordingly 
        #      return the HttpResponse ( "get brother") 
        IF request.method == ' the POST ' :
             return the HttpResponse ( ' coming baby ')
        return render(request,'login.html')

Database Related

django default sqlite database that comes with it if you want a different database needs to be configured in the configuration file settings

1.settings configuration file

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

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

import pymysql
pymysql.install_as_MySQLdb()

ORM related

Object-relational mapping:

Table ----------> class

Record ---------> Objects

Attribute field value corresponding -----> object

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 the 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

Database migration command

manage.py makemigrations python3 
# only in a small notebook (migrations folder) and modify the database records are not directly manipulate data 

python3 manage.py the migrate 
# modify the database record actually synchronized to the database 
# Note: As long as the models move in with database-related code must be re-implementation of 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. to set default values for the new field

# Examples 
addr = models.CharField (= 32 MAX_LENGTH, default = ' China ' )   # default value of this field defaults

2. Give the new field to be empty

models.IntegerField = Age (null = True)   # This field allows null

delete

Delete the comment field directly in the field models.py and then re-execute two commands to
note: delete all of the data in the table fields corresponding to all after the execution, and under normal circumstances is basically not used in the true sense deleted

change

Directly modify field properties, after the same delete, re-execute two commands to

Deletions data change search operation

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

from app01 import models

Check data

# All 
models.User.objects.all ()   # direct to get all the data 
# SQL statements should be * from the User the SELECT 

# single     
models.User.objects.get (username = username)   # by the get method to take, will not get error 

models.User.objects.filter (username = username) .first ()   # get the list of the first data object 

 "" " 
        filter out the query result is a" place in the list is a list of a data object itself " 
        when a query absence of 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 
 " "" 
"" " 
        not recommended because once the index value no data re-index values will complain 
        but if the first is internal, although according to the index value but no data no error will be returned None 
"" "

important point:

= = models.User.objects.filter USER_OBJ RES (username = username)
 Print (RES)
 "" " 
RES is a querSet objects, it can operate as a list of index values may be taken by (QuerySet supports only positive indexes do not support negative) also supports the slicing operation (cut out the result was a querySet objects) but do not recommend you do that 
. "" " 
# About querySet objects 
" "" 
querySet object can point to view the sql query statement 
. "" " 

# on first () method 
"" " 
    I do not recommend that you use an index value because there is no data once again being given an index value of querSet objects 
    but if the first is internal, although according to the index value but no data no error will be returned None 
." ""

Increased data

# ORM insert data 
        # 1.Create () 
# RES models.User.objects.create = (username = username, password = password)   
# SQL statement INTO the User shall INSERT (username, password) values (username, password) 
        "" " 
        Create new data and the method can return a value 
        return value is the new data object itself 
        ." "" 
        # 2 using the object 
USER_OBJ = models.User (username = username, password = password) 
user_obj.save ()

Delete data

Delete logical and change are based on existing data carried out, so we are the first to get the idea that it needs to change the id value, and then get the data can be modified

request.GET.get ( ' the above mentioned id ' )
 # be careful not thinking the relationship between post request is a request to obtain the parameters get carried
models.User.objects.filter(id=delete_id).delete()  
#对应的SQL语句为delete from user where id = delete_id;

Change data

The same logic to change deleted primary key must first get the data, and then we want to show the need to modify the data on the page, allowing users to modify their own, the idea is to first determine the user's request is a GET or POST, GET if it is returned to the user a page that allows data to fill in with a fox on the page, and then we get the data to be modified again

# Update data 
        # way a: 
        # models.User.objects.filter (the above mentioned id = edit_id) .Update (username = username, password = password) 
# SQL statement to the SET username = username the User Update, the WHERE password = password the above mentioned id = edit_id 
        " "" 
        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 very inefficient 
        ." ""

Guess you like

Origin www.cnblogs.com/wangnanfei/p/11529146.html