django fourth day of class summary

day17 
. ###. 1 Recap 
- 1.orm 
    - Parameter 
        - null blank default ((1, ' M'), ()) 
    
    - 1 must know will be 13 
        - 1. Return a list of objects 
            - All ()   
            - filter () 
            - the exclude () 
            - values () {} 
            - values_list ( 'ID', 'name') () 
            - ORDER_BY () -    
            - Reverse () 
            - DISTINCT () 
        - returns the object 2. 
            - GET () 
            - First () 
            - Last () 
        - returns 3. 
            - COUNT () 
        - returns a boolean 4. 
            - EXISTS () 
    
    double underlined table 2. single -
        - __gt lt GTE LTE 
        - __in = [] __range = [] 
        - ignore case __contains like __icontains 
        - __startswith __endswith 
        - __istartswith __iendswith 
        - __isnull = True 
        
    - 3. Foreign Key 
        - indicates many to one relationship 
        - BOOK: 
            - = Pub Models .ForeignKey (Publisher, on_delete = models.CASCADE, null =) 
            
        target book_obj.pub _> associated - 
        - book_obj.pub_id 
        - book_obj.pub.name 
        
        - not set the related_name 
        - pub_obj.book_set _> relationship management Object 
        - pub_obj. book_set.all () 
        
        - set = the related_name 'Books' 
        - pub_obj.books.all ()
        
        - models.BooK.objects.filter (pub__name = 'XXX')
        - models.Publisher.objects.filter (book__name = 'XXX') 
        
    - 4.-many 
        - many relationship represented by 
        - Book 
            - author 
        - author 
        
        - book_obj.author _> Relationship Management Object 
        - book_obj.author.all ( ) 
        - book_obj.author.set ([]) [Object, Object] [ID, ID] 
        - book_obj.author.add () object, the object ID, ID 
        - book_obj.author.remove () 
        - book_obj.author.clear ( ) 
        - book_obj.author.create () Create a Study 
        
    - The packet aggregation and 
        `` `Python 
        from django.db.models Import max, Min, the Sum, Avg., the Count
        
        models.Book.objects.aggregate(max=Max('price'))   {'max':100}        
        
        models.Author.objects.annotate(Max('books__price')).values()  对象列表        
        
        models.Book.objects.values('author').annotate(Max('price'))
        ```
                
    - 6.F Q  
        - filter(sale__gt=F('store'))
        
        - update(sale=F('sale')*2+13)
        
        - Q(Q(id__gt=1) | Q(id__lt=5))  Q()
        - & | ~
                
    - 7.事务
        - begin;  
        - commit;
        ```python
        from django.db import transaction
        import time

        try:
            with transaction.atomic():
                # Series of operations
                models.Publisher.objects.create (name = 'xxxxxx')               

        except Exception as e:
            Print (E) 
        `` ` 
        
- 2.cookie the session     
    - 1.cookie 
        - a bundle of keys stored on the browser of 
       
        - setting         
            - response.set_cookie (Key, value, Age-= max. 5) 
            
        - Get 
            - request .COOKIES [] .get 
            
        - delete 
            - response.delete_cookie (Key) 
            
    - 2.session 
        - stored on the server of a bundle of key-value pairs, depending on the cookie 
        - request.session [k] = v 
        - request.session [k]   
        - request.session.delete () 
        - request.session.flush () 
			
### 2 today language 
- 1. middleware 
    - https://www.cnblogs.com/maple-shaw/articles/9333824.html 
    - intermediate is a member class, the request and response processing django. five methods
    - performing sequential execution time parameter return value 
    
    - process_request (Self, request) 
        - Parameters: 
            - request request the same function with a view 
            
        - Time: 
            - a view function is executed before, also the route matching before 
            
        - the order of execution: 
            - in accordance with the order registration is performed 
        
        - return value: 
            - None: normal flow   
            - the HttpResponse: 
                - middleware process_request current route matches the view function is not performed after the intermediate 
                - direct execution method process_response current middleware, the remaining normal process results returned to the browser 
    
    - process_response (Self, request, the Response) 
        - parameters: 
            - request with the view function in the same request 
            - response response objects 
            
        - execution time: 
            - after the view function execution 
            
        - the order of execution: 
            - descending performed in the order of registration 
        
        - Return Value:             
            - HttpResponse: must return HttpResponse object 
                      
    - process_view (Self, request, view_func, view_args, view_kwargs) 
        - Parameters: 
            - request with the view function request with a 
            - view_func view function 
            - view_args positional parameters passed to the view function 
            - view_kwargs to the view function key configuration parameters 
            
        : - execution time 
            before and after the view function is executed, also the route matching - 
            
        - execution order: 
            - in the order in registration order 
        
        - return value: 
            - None: normal flow   
            - the HttpResponse: 
                - process_view view middleware function is not executed after the current middleware 
                - direct execution method last process_response middleware, leaving the normal process to return the results to the browser 
    
    - process_exception (self, request, exception ): 
        - parameters: 
            - request with the same request view function 
            - exception error object 
            
        : - the execution time (trigger condition) 
            after an error View - before the execution 
            
        - the order of execution: 
            - executed in reverse order of registration 
        
        - the return value: 
            - None: the normal process to the next processing middleware is not an exception handling to deal with django 
            - HttpResponse: 
                - process_exception middleware after the current middleware do not perform 
                - direct execution method last process_response middleware, leaving the normal process to return the results to the browser 
    
    - process_template_response (Self, request, the Response): 
        - parameters: 
            - request with the view function in the same request 
            - response template_response objects
            
        - execution time (trigger conditions):  
            - view function returns an object template_response
            
        - the order of execution: 
            - executed in reverse order of registration 
        
        - the return value: 
            - HttpResponse: the object must return template_response 

    
- 2.ajax 
    - https://www.cnblogs.com/maple-shaw/articles/ 9524153.html 
    
    - requesting by: 
        - the input address 1. GET browser address 
        - 2.form form GET / the POST 
        - 3.a tag GET 
        
    - Ajax JS technology, data transmission request, the transmission of XML JSON 
        - partial refresh asynchronous 
    
    - calculation example 1. 
        - [] + [] = [] 
        
        `` `JavaScript 
        $ .ajax ({ 
            URL: '/ Calc /', 
            type: 'POST', 
            Data: { 
                A1: $ ( 'INPUT [name = "ii1"] '). val (),
                A2: $ ( 'INPUT [name = "II2"]') Val (),.  
            },
            Success: function (RET) { 
                $ ( 'INPUT [name = "II3"]') Val (RET). 

            } 
        })	 
        `` ` 
        
    - 2.ajax parameters introduced 
        
        ` `` JavaScript 
        $ .ajax ({ 
            url: '/ the Upload /', // upload the address 
            type: 'post', // type of request 
            processData: false, // jQuery told not to go processing data transmitted 
            contentType: false, // do not tell jQuery request to set the Content-Type header 
            data: form_data, // data} { 
            Success: function (RET) {   
                the console.log (RET) 

            }, 
            error: function (RET) {
                Alert (RET) 
            } 

        }) 
            username = forms.CharField ( label = 'username', min_length = 6) 
         `` `        
    
    - Set post 3. Submit request 
        - the premise csrftroken Cookie 
        - csrfmiddlewaretoken added to the key-value 1.data 
        - 2.headers: { 
            'csrftoken-X': $ ( 'INPUT [name = "csrfmiddlewaretoken"]'). Val (), 
        } 
        - introduction 3. file 

- 3.form assembly 
    https://www.cnblogs.com/maple-shaw/articles/9537309.html - 
    
    - effect of form components: 
        - 1. the input frame generated automatically 
        - 2 . data can be verified 
        - 3. there are error 
    
    - 1. registration example 

    - use 2.form assembly 
        `` `Python 

        class regform (forms.Form): 
        ` `` Python
            password = forms.CharField (label = 'password', the widget = forms.PasswordInput) 
         
        `` `    
            
        - View: 

            form_obj = regform () 
            
            form_obj = regform (of request.POST)   
            form_obj.is_valid () # verification data 
            
            form_obj .cleaned_data # verification data only through 
            
            return the render (Request, 'reg.html', { 'form_obj': form_obj}) 
        `` `     
            
        - template: 
            - {} {} form_obj.as_p demo                      
            - {{form_obj.username }} input frame 
            - {{form_obj.username.label}} label values 
            - {{form_obj.username.id_for_label}} input frame id
            - {{form_obj.username.errors}} error fields all current 
            - {{form_obj.username.errors.0}} The first error current field               
            - {{form_obj.non_field_errors}} __all__ global error 
     
    - 3. parameter field and introduction    
        - CharField 
        - ChoiceField 
        - MultipleChoiceField         
        
        - = True required, whether to allow null 
        - widget = None, HTML widget 
        - label = None, or for generating a display content label label 
        - initial = None, the initial value 
        - help_text = '', help information (in display next tab) 
        - error_messages, = None, an error message { 'required': 'not empty', 'invalid': 'malformed'} 
        - validators = [], custom validation rules
        - disabled = False, whether to edit	 
        
    - Checksum 4. Built custom validation 
        - required 
        - MAX_LENGTH 
        - min_length 
        
        - 1. Use the built verifier 
        `` `Python 
 
            from django.core.validators import RegexValidator

            Phone = forms.CharField ( 
                validators = [RegexValidator (R & lt '^ 1 [3-9] \ d {9} $', ' phone number format is incorrect')], 
            )       
        `` ` 
        
        - 2 custom function 
        ` Python 
       
            from the ValidationError django.core.exceptions Import 
            DEF check_username (value): 
                IF 'alex' in value: 
                    The raise ValidationError ( 'user name contains illegal characters, please re-select') 
        
        `` ` 
        
    - 5.is_valid source code analysis and local, global hook
     
        `` `Python 

         DEF clean_username (Self) : 
             # local hooks on the current field validator 
             # by check returns the current value of the field 
             # does not throw an exception by checking ValidationError 
            pass 

         DEF Clean (Self):
            All Hook # validator any field 
            # returned by checking the value of all the fields 
            # does not throw exceptions by checking __all__ is the ValidationError 
            password = self.cleaned_data.get ( 'password') 
            re_password = self.cleaned_data.get ( 're_password ') 
            IF == re_password password: 
                return self.cleaned_data 
            self.add_error (' re_password ',' two passwords do not match !!!! ') 
            The raise the ValidationError (' two passwords do not match ')     
         
         `

 

Guess you like

Origin www.cnblogs.com/lilyxiaoyy/p/11372112.html