Three ways to create many-ways and forms assembly session cookie

1. Automatic (recommended *)
            advantage: you do not need to manually create a third table
            is insufficient: Since the third table than you created manually, which means the third table is fixed and can not do field expansion

class Book(models.Model):
  title = models.CharField(max_length=32)
  price = models.DecimalField(max_digits=8,decimal_places=2)
  authors = models.ManyToManyField(to='Author')

class Author(models.Model):
  name = models.CharField(max_length=32)

 2. Pure manual (to understand)
            create your own third table
            advantages: the third extension field can be any
            shortage: orm query is not convenient

class Book(models.Model):
  title = models.CharField(max_length=32)
  price = models.DecimalField(max_digits=8,decimal_places=2)

class Author(models.Model):
  name = models.CharField(max_length=32)
                            
class Book2Author(models.Model):
  book = models.ForeignKey(to='Book')
  author = models.ForeignKey(to='Author')
  create_time = models.DateField(auto_now_add=True)

3. Semi-Automatic (recommended ******)
            Advantage: combines the advantages of two pure automatic and manual

class Book(models.Model):
    title = models.CharField(max_length=32)
    price = models.DecimalField(max_digits=8,decimal_places=2)
    authors = models.ManyToManyField(to='Author',through='Book2Author',through_fields=('book','author'))

class Author(models.Model):
    name = models.CharField(max_length=32)

class Book2Author(models.Model):
    book = models.ForeignKey(to='Book')
    author = models.ForeignKey(to='Author')
    create_time = models.DateField(auto_now_add=True)

forms the basic component usage

from Django Import Forms 

class the LoginForm (forms.Form): 
    username = forms.CharField (= MAX_LENGTH. 8, min_length =. 3)   # username shortest longest eight three 
    password = forms.CharField (max_length = 8,   min_length = 5) # maximum password eight minimum five 
    Email forms.EmailField = ()   # Email must be a mailbox format

Basic use

In the verification pyton Console 
from
app01 Import views . 1 will be verified data to the instance of the class object is generated in the custom dictionary manner. Form_obj = views.LoginForm ({ ' username ' : ' Jason ' , ' password ' : ' 123 ' , ' Email ' : ' 123 ' }) 2 . how to check whether all legal data form_obj.is_valid () # only all the data are in line with the requirements will be True False 3 how to view the error cause. form_obj.errors { ' password ': [ ' . Ensure® Least AT has the this value. 5 characters (IT has. 3) ' ], ' In Email ' : [ ' the Enter A Valid In Email address. ' ] } . 4 how to view data verification. Form_obj.cleaned_data { ' username ' : ' Jason ' }

Notes:
     1. Custom class in all fields are necessary to pass the default value of
      2. The additional incoming class may not defined field names forms component does not go check means that multi-pass had nothing

Rendering page

<p> The first way to render the page (high degree of encapsulation is generally used for local testing is not generally applicable) </ P> 
    {form_obj.as_p} {}   
    {} {form_obj.as_ul} 
    {} {} form_obj.as_table
                
 <p> the second embodiment is to render the page (higher scalability trouble writing) </ P> 
    <p> form_obj.username.label {} {} {} {} form_obj.username </ P> 
    <p> { form_obj.password.label {} {} {}} form_obj.password </ P> 
    <P> {{{{form_obj.email form_obj.email.label}}}} </ P> 
                
<P> third page is rendered fashion (recommended) </ P> 
    { % for foo in form_obj% }
         <P> foo.label {} {} {} {} foo </ P> 
    { %} endfor%

Note
    1.forms component will render the label to obtain user input in rendering pages to help you when you need to manually add the submit button         
     class field case 2.input comment box label does not specify a default with the first letter capitalized

Browser distal canceled check function
                form tag to specify attributes novalidate
                <form action = "" method = 'post' novalidate> </ form>

Display error messages

front end

<form action="" method="post">
    {% for foo in form_obj %}
        <p>{{ foo.label }}:{{ foo }}
        <span>{{ foo.errors.0 }}</span>
        </p>
    {% endfor %}

rear end

= forms.CharField password (= MAX_LENGTH. 8, min_length =. 5, label = ' password ' , error_messages, = {
                                    ' MAX_LENGTH ' : ' password maximum eight ' ,
                                    ' min_length ' : ' minimum password five ' ,
                                    ' required ' : ' password can not be empty ' 
                               }, required = False, validators = [RegexValidator (R & lt ' ^ [0-9] + $ ' , 'Please enter the number '), RegexValidator (R & lt ' ^ 159 [0-9] + $ ' , ' number must start 159 ' )])   # password shortest longest eight five

Hook function (HOOK)

Usage: In the form of a custom class method of writing to
 # local hook (make additional validation for a field) can not validate the user name 666 contained once with tips 
    DEF clean_username (Self): 
        username = self.cleaned_data. GET ( ' username ' )
         IF  ' 666 '  in username: 
            self.add_error ( ' username ' , ' light is not enough to call 666 on you have to own ' )
         return username
         # global hook (to do extra check for multiple fields) checking whether the user password twice consistent 
    DEF Clean (Self): 
        password = self.cleaned_data.get ( ' password ')
        confirm_password = self.cleaned_data.get('confirm_password')
        if not password == confirm_password:
            self.add_error('confirm_password','两次密码不一致')
        return self.cleaned_data

cookie and session
        due to the http protocol is stateless can not record the user's status       
      

   cookie key is stored on the client browser of
            works: When you log in successfully saved some of the information on the browser, and then visit the next time it will take this information to access the server through the server information to identify your identity           
            cookie, though written in the client browser but the server is set up, the browser can choose not to obey an order prohibiting write cookie
                 
        session key is stored on the server for the
            session is stored on the server though keys on the right, but it is dependent on the work of the cookie, the server returns to the browser a random string, the browser stores in the form of key-value pairs
            sessionid: random string
            
            browser when accessing the server will the random string-carrying, the rear end of the rear end obtain records of random strings do match
                random string 1: 1 data
                random string 2: data 2

设置session     request.session['name'] = 'jason'

获取session     request.session.get('name')

django session default timeout is 14 days

django_session table a record for a browser

request.session.delete () # sessionid information is deleted browser

request.session.flush () # will remove all the browser and server

 

Setting Session Session and Cookie timeout
        request.session.set_expiry (value)
            * If the value is an integer, session will expire after some number of seconds.
            * If the value is datatime or timedelta, session will expire after this time.
            * If the value is 0, the user closes the browser session will fail.
            * If the value is None, session will depend on the global session expiration policy.

Guess you like

Origin www.cnblogs.com/zrh-960906/p/11580907.html