Python Learning 19th Day Django Knowledge

Source: Internet
Author: User

One, Django Knowledge summary

1, label of the same name property, multiple values get

<form action= "/login/" method= "POST" enctype= "Multipart/form-data" >        <p>            <input type= "text" Name= "user" placeholder= "username"/>        </p>        <p>            <input type= "password" name= "pwd" placeholder= "Password"/>        </p>        <p>            male: <input type= "Radio"  name= "Gender" value= "1"/>            female: <input type= "Radio" name= "Gender" value= "2"/>            Publicity: <input type= "Radio" name= "Gender" value= "3"/ >        </p>        <p>            male: <input type= "checkbox"  name= "favor" value= "one"/>            female: <input type= "checkbox" Name= "Favor" value= "/>"            : <input type= "checkbox" Name= "Favor" value= "33"/ >        </p><from>view.py function    v = Request. Post.getlist (' favor ')

2,select Label Multiple selection

<p>            <select name= "City" multiple>                               #select标签添加multiple属性                <option value= "sh" > Shanghai </ option>                <option value= "BJ" > Beijing </option>                <option value= "TJ" > Tianjin </option>            </select> </p>

3, File Upload


<form action= "/login/" method= "POST" enctype= "Multipart/form-data" >
view.py
obj = Request. Files.get (' Fafafa ')
Print (Obj,type (obj), obj.name) Import Osfile_path = Os.path.join (' upload ', obj.name) F = open (File_path, mode= "WB") for I In Obj.chunks (): f.write (i) f.close ()

4, template language loop operation dictionary

view.py definition Dictionary user_dict = {     ' k1 ': ' root1 ',     ' K2 ': ' Root2 ', ' K3 ': ' root3 ', ' K4 ': ' Root4 '     ,}tamplates In the HTML template read {% for k,row in user_dict.items%}    <li>{{k}}-{{row}}</li>{% endfor%}

5,tamplates HTML Gets the value in the dictionary

Html
1, jump HTML <li><a target= "_blank" href= "/detail-{{k}}.html" >{{Row.name}} </a></li>
2, jump htmlurl.py
URL (r ' ^detail-(\d+). html ', Views.detail),

6,django URL Regular match

(1) in the Django URL to pass parameters, sent to the back end of the views.py in the processing function, sometimes encountered a number of arguments, such as the URL (r ' ^detail-(\d+)-(\d+). html ', Views.detail), Received in the views.py function, def detail (request,nid,uid), the function definition passed in multiple form parameters, to receive the URL of the variable, and the value of the variable and the detail function parameter position is consistent,

(2) Add in the Django URL? P, determine the variable name corresponding to the parameter in the URL so that the form parameter position defined in the detail function can be placed arbitrarily

URL (r ' ^detail-(? p<nid>\d+)-(? p<uid>\d+). html ', views.detail) def detail (Request,uid,nid) def detail (request,nid,uid)                                                    #都可以自行接收自己的值     

(3) The WIEWS.Y function receives multiple parameters def detail (Request,*args,**kwargs) *args is the form of a tuple to receive parameters, **kwargs is to receive parameters in the form of a dictionary

Summarize

A.  A single regular expression URL in the URL (r ' ^detail-(\d+)-(\d+). html ', Views.detail), Def func (Request, NID, UID):p assdef func (Request, *args): args = (2,9) def func (Request, *args, **kwargs): args = (2,9)   B.   The regular expression in the URL defines the URL in key.value form (R ' ^detail-(? p<nid>\d+)-(? p<uid>\d+). html ', Views.detail)
def func (Request, NID, UID):p assdef funct (Request, **kwargs): Kwargs = {' nid ': 1, ' uid ': 3}def func (Request, *args, **kwarg s): args = (2,9)

7,django the Name property in the URL to name the URL routing relationship

(1) In the URL, you can set an alias for a URL such as (' R ' Indexaaaabbbaa ', views.index,name= "index")

(2) reference in templates HTML <form action= "{% url ' index '%}" method= "POST" ></form>

(3) <form action= "{{request.path_info}}" method= "POST" ></form> after submission, jump to this page, Path_info get the current URL

(4) rewrite the URL in the wiews.py function

From Django.urls Import reversedef Index (Request):    v=reverse (' Indexx ')    print (v)                              #v为生成的url when the URL such as URL (r ' index ', index,name= "Indexx") def index (Request,nid):    v=reverse (' Indexx ' args= (All))        #当url For example URL (r ' index/(\d+)/', index,name= "Indexx") with one parameter
def index (Request,nid,vid):
V=reverse (' Indexx ', args= (90,10,)) #当url with multiple parameters such as URL (R ' index/(\d+)/(\d+)/', index,name= "Indexx")
def index (Request,nid,vid):
V=reverse (' Indexx ', kwargs={' nid ': 1, ' vid ': ten} #当url中含? p When for example URL (r ' index/(? p<nid>\d+)/(? p<uid>\d+)/', index,name= "Indexx")
#form the value <form action= "{% url ' index ' nid=1 uid=3%}" method= "POST" ></form>

(5) URL classification, multiple app URL distribution

Add the URL of the app to the URL under the main program Django project

URL (r ' ^cmdb/', include ("App01.urls")), #到app01中加载app01的urls文件

URL (r ' ^monitor/', include ("App02.urls")), #到app02中加载app02的urls文件

8,django ORM Operations Database

1, create a database

(1) Create a class

From django.db import models# App01_userinfoclass UserInfo (models. Model):        # id column, auto increment, primary key username = models. Charfield (max_length=32)   # ID column, auto increment, primary key password = models. Charfield (max_length=64)    # User Name list, string type, specified length

(2) Register app

Installed_apps = [' django.contrib.admin ', ' Django.contrib.auth ', ' django.contrib.contenttypes ', ' Django.contrib.sessions ', ' django.contrib.messages ', ' django.contrib.staticfiles ', ' app01 ',]

(3) Execution of orders

Python manage.py  makemigrationspython manage.py  Migrate

(4) Note

#Django默认使用MySQLdb模块链接MySQL # actively modify to Pymysql, add the following code to the __init__ file under Project's folder with the same name: #import Pymysql#pymysql.install_as_ MySQLdb ()

2, Data write

Method One:

Models. UserInfo.objects.create (username= "root", password= "123")

Method Two:

Dict = {' username ': ' Eric ', ' Password ': ' 123 '}

Models. UserInfo.objects.create (**dict)

Method Three:

obj = models. UserInfo (username= ' Jack ', password= ' 123 ')

Obj.save ()

3, Data Lookup

(1) Check all result = models. UserInfo.objects.all ()

The result is the Queryset type, the Django data type, which can be viewed as a list, how many data are in the table, how many elements are in the list, and each element is actually an obj object, and the object contains every field of the table, for example [obj (ID, Username,password), obj (Id,username,password), obj (Id,username,password)], the final reading can be in the following code

For row in result:    print (Row.id,row.username,row.password)

(2) According to the condition check value result = models. UserInfo.object.filter (username= ' root ')

result = models. UserInfo.object.filter (username= ' root ', password= ' 123 ') equals and username and password

4, Data deletion

result = models. UserInfo.object.filter (username= ' root ', password= ' 123 '). Delete () deletes this row data

5, data modification

result = models. UserInfor.object.filter (username= ' root ', password= ' 123 '). Update (password= "666")

6. Other methods of data manipulation

Models. UserInfo.object.filter (password= ' 123 '). First () find the number of a. COUNT ()

9,django Admin Configuration

(1) Create a background administrator Python manage.py createsuperuser

(2) Configure the background management URL URL (r ' ^admin/', admin.site.urls)

(3) Registering and configuring the Django Admin page

1, open admin.py, configure the following

From django.contrib import admin from  APP01 import  models  Admin.site.register (models. usertype) Admin.site.register (models. UserInfo) Admin.site.register (models. UserGroup) Admin.site.register (models. Asset)

2, set the data table name

Class Usertype (models. Model):    name = models. Charfield (max_length=50)      class Meta:        verbose_name = ' user type '        verbose_name_plural = ' user type '

10,django models Field type

Overall includes five categories: (1) string (2) Number (3) time (4) binary (5) Self-increment type

Autofield (Field)-int self-increment, must be filled in parameter primary_key=true
For example
Class UserGroup:
    UID = models. Autofield (primary_key=true) Bigautofield (Autofield)-bigint self-increment, you must fill in the Parameters primary_key=true Note: When the model does not have a self-increment column, Automatically creates a column named ID from django.db Import models Class UserInfo (models. Model): # automatically creates a column named ID and an integer column with an increment of username = models. Charfield (MAX_LENGTH=32) class Group (models. Model): # Custom Auto-increment nid = models. Autofield (primary_key=true) name = models. Charfield (max_length=32) Smallintegerfield (Integerfield):-Small integer -32768 ~ 32767 Positivesmallintegerfield (Posi Tiveintegerreldbtypemixin, Integerfield)-positive small integer 0 ~ 32767 integerfield (Field)-integer sequence (signed)-2147483648 ~ 2 147483647 Positiveintegerfield (Positiveintegerreldbtypemixin, Integerfield)-positive integer 0 ~ 2147483647 BigIntegerFi Eld (Integerfield):-Long Integer (signed)-9223372036854775808 ~ 9223372036854775807 Custom unsigned integer field class Unsignedintege Rfield (models. Integerfield): Def db_type (self, connectION): Return ' integer UNSIGNED ' PS: The returned value is the property of the field in the database, the default value for the Django field is: ' Autofield ': ' Integer A Uto_increment ', ' Bigautofield ': ' bigint auto_increment ', ' Binaryfield ': ' Longblob ', ' Bool ' Eanfield ': ' bool ', ' charfield ': ' varchar (% (max_length) s) ', ' commaseparatedintegerfield ': ' varchar (% ( Max_length) s) ', ' Datefield ': ' Date ', ' Datetimefield ': ' DateTime ', ' Decimalfield ': ' Numeri C (% (max_digits) s,% (decimal_places) s) ', ' Durationfield ': ' bigint ', ' filefield ': ' varchar (% (max_lengt h) s) ', ' filepathfield ': ' varchar (% (max_length) s) ', ' Floatfield ': ' Double precision ', ' Int ' Egerfield ': ' Integer ', ' Bigintegerfield ': ' bigint ', ' Ipaddressfield ': ' char ', ' generi Cipaddressfield ': ' char ', ' nullbooleanfield ': ' bool ', ' Onetoonefield ': ' Integer ', ' Po ' Sitiveintegerfield ': ' InTeger UNSIGNED ', ' positivesmallintegerfield ': ' smallint UNSIGNED ', ' slugfield ': ' varchar (% (max_lengt h) s) ', ' Smallintegerfield ': ' smallint ', ' TextField ': ' Longtext ', ' Timefield ': ' Time ', ' Uuidfield ': ' char (+) ', Booleanfield (field)-Boolean type Nullbooleanfield (field):-Nullable Boolean value Ch Arfield (field)-character type-the max_length parameter must be supplied, Max_length represents the character length TextField (field)-Text type Emailfield (C Harfield):-String type, Django Admin and Modelform provide validation mechanism Ipaddressfield (Field)-string type, Django Admin and Modelform For validation IPV4 mechanism Genericipaddressfield (Field)-string type, Django admin and Modelform provide validation Ipv4 and Ipv6-parameters: protocol, used to specify Ipv4 or Ipv6, ' both ', ' IPv4 ', ' IPv6 ' Unpack_ipv4, if specified as true, enter:: ffff:192.0.2.1, can be resolved to 192.0.2.1, opening the Thorn function, need To Protocol= "both" Urlfield (Charfield)-string type, Django admin and Modelform provide authentication URL Slugfield (Charfield)-word Type of string, Django admin and modelThe form provides validation support for letters, numbers, underscores, connectors (minus) Commaseparatedintegerfield (Charfield)-string type, the format must be comma-delimited number Uuidfield (Field) -String type, Django Admin and Modelform provide validation of UUID format Filepathfield (Field)-string, Django Admin and Modelform provide read folder files Can-parameters: path, folder path Match=none, regular match Recursive=false, recursively under the folder Allow_files=true, allow file Allow_folders=false, Allow folder Filefield (Field)-string, path saved in database, file upload to specified directory-parameter: upload_to = "" "Save path of uploaded file Storage = None Storage component, default Django.core.files.storage.FileSystemStorage ImageField (Filefield)-string, path saved in number According to the library, the file is uploaded to the specified directory-parameter: upload_to = "" The Save path of the uploaded file storage = None Storage component, default Django.core.files . Storage. Filesystemstorage Width_field=none, upload a picture of the height of the Saved database field name (string) Height_field=none the width of the uploaded picture save the database field name (string ) DatetimefiEld (Datefield)-date + time format Yyyy-mm-dd Hh:mm[:ss[.uuuuuu]][tz] Datefield (datetimecheckmixin, Field)-date format Yyyy-mm-dd Timefield (datetimecheckmixin, field)-time format hh:mm[:ss[.uuuuuu]] Durationfield (field) -Long integer, time interval, database in accordance with bigint storage, ORM Gets the value of Datetime.timedelta type Floatfield (field)-floating-point type Decimalfield (field) -10 Decimal Fractions-parameters: max_digits, fractional total length decimal_places, decimal length Binaryfield (Field)-binary type

   Django models field restriction parameters

Null #db是否可以为空 =truedefault # default = "" Primary_key                                   #主键 =truedb_column #列名 = "User" Db_index                            #索引 =trueunique #唯一索引 =trueunique_for_date #只对时间做索引 Unique_for_month #只对月份做索引unique_for_year #只对年份做索引 Auto_now #创建时, auto-generate time Auto_now_add #更新时, automatically updated to current time # O                           BJ = UserGroup.objects.filter (id=1). Update (caption= ' CEO ') is not updated # obj = UserGroup.objects.filter (id=1). First () Update # obj.caption = "CEO" # obj.save () choices #django the dropdown shown in admin box to avoid a table query class UserInfo (models. Model): Username = models. Charfield (max_length=32) user_type_choices = ((1, ' Super user '), (2, ' normal user '), (3, ' General user '), user_type_id = models. Integerfield (choices=user_type_choices,default=1) blank #django admin can be empty Verbos E_name #django admin Display field Chinese editable #django admin can be edited E Rror_messages #错误信help_text #django Admin tip validators

 12,django  models foreign key settings

Class UserGroup (models. Model): uid = models. Autofield (primary_key=true) caption = models. Charfield (max_length=32,unique=true) CTime = models. Datetimefield (Auto_now_add=true, null=true) uptime = models. Datetimefield (Auto_now=true, null=true) # user_list = Userinfo.objects.all () # reads a Queryset list object, encapsulates the Id,username, email,user_group_id, in user_group_id, also encapsulates the UID and caption# [obj (id,username,email,user_group_id,,user_group_id (UID, Caption)), obj,obj]# for row in user_list:# print (row.user_group_id) # print (row.user_group.uid) # print (Row.user _group.caption) class UserInfo (models. Model): # ID column, auto increment, primary key # user name, string type, specified length # string, number, time, binary username = models. Charfield (max_length=32,blank=true,verbose_name= ' username ') Password = models. Charfield (max_length=60, help_text= ' pwd ') email = models. Charfield (max_length=60) test = models. Emailfield (max_length=19,null=true,error_messages={' invalid ': ' Please enter password '}) # user_group_id number User_group = models. ForeignKey ("UserGroup", To_field= ' uid ') # (Uid,catption,ctime,uptimew) user_type_choices = ((1, ' Super user '), (2, ' normal user '), (3, ' Grandhotel Pupp General customers '),

Python Learning 19th Day Django Knowledge

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.