All the way by the system URL
1 URL (r ' ^index/', views.index) URL (r ' ^home/', views. Home.as_view ())
2 URL (r ' ^detail-(\d+). html ', views.detail), #动态路由
views.py
def detail (Request,nid)
URL (r ' ^detail-(\d+) _ (\d+). html ', views.detail), #动态路由
def detail (Request,nid,uid)
3 URL (r ' ^detail-(? p<nid>\d+) _ (? p<uid>\d+). html ', views.detail), #关键字分组
def detail (Request,*args,**kwargs)
args[index]# Index
Kwargs[key]
4 Name
Name the URL routing relationship, and later you can generate the URL you want based on this name
URL (r ' ABCD ', views.detail,name= ' indexx1 '), #定义url name
Template language {% url ' indexx1 '%}
def func (Request,*args,**kwargs):
From Django.urls Import Reverse
Indexx1=reverse (' indexx1) ' # url=/abcd/
URL (r ' fff/(\d+)/', views.detail,name= ' indexx2 '), #定义url name
Template language {% url ' indexx2 ' 2%}
def func (Request,*args,**kwargs):
From Django.urls Import Reverse
Indexx2=reverse (' indexx2 ', args= () ' #url =/fff/1/2/
URL (r ' ggg/? P<nid> (\d+)/? P<uin> (\d+)/', views.detail,name= ' indexx3 '), #定义url name
Template language {% url ' indexx3 ' nid=1 uid=3%}
def func (Request,*args,**kwargs):
From Django.urls Import Reverse
Indexx3=reverse (' indexx2 ', kwargs= (nid=1,uid=2) ' # URL=/GGG/1/2
Form action = ' {%url ' Indexx ' 2%} #表单 submitted URL
#request. Path_info: The URL of the current page
Form action = ' {{request.path_info}} #表单 the submitted URL is the current page
5 Routing distribution
From Django.conf.urls import include
Main route:
urlpatterns=[
URL (r ' ^cmdb/', include (' Cmdb.urls ') #分路由
URL (r ' ^monitor/', include (' Monitor.urls ') #分路由
]
Tap by: CMDB
urlpatterns=[
URL (r ' ^login/', Views.login ')
URL (r ' ^index/', Views.index ')
]
Two views
1 Getting user request data
Request. GET
Request. POST
Request. FILES
Get: Get Data
POST: Submit Data
#多选
2.checkbox and more selection of content
Request. Post.getlist ()
3. #上传文件 Form Tag Add Property enctype=multipart/form-data
Obj.request.FILES.get (' filename ')
Obj.name #文件名
File_path=os.path.join (' File_dir ', obj.name)
F=open (file_path,mode= ' WB ')
For I in Obj.chunks ()
F.write (i)
F.close ()
Three templates
Quad ORM operation
SELECT * from TB where ID >1
#对应关系
Models.tb.objects.filter (id_gt=1) #查询
1 Creating a Class
A from django.db import models
Class UserInfo (models. Model):
#自动创建 self-increment ID primary key
#用户名列, the string type specifies the length
Username=models. Charfield (MAX_LENGTH=32)
Password=models. Charfield (MAX_LENGTH=32)
Python manage.py makemigrations
Python manage.py Migrate
B. Use
Installed_apps = [
' Django.contrib.admin ',
' Django.contrib.auth ',
' Django.contrib.contenttypes ',
' Django.contrib.sessions ',
' Django.contrib.messages ',
' Django.contrib.staticfiles ',
' Newapp ', #指定对应的app
]
C. Execution of orders
Python manage.py makemigrations #查看数据库表的修改记录
Python manage.py migrate #创建 database and table structure
D. ########## #连接使用Mysql attention #################
Django uses the MySQLdb module to connect to MySQL by default
Active modification to Pymysql: in the __init__ file under Project name folder
Import Pymysql
Pymysql.install_as_mysqldb ()
-Automatically create database tables based on class
Python manage.py makemigrations #数据库修改日记
Python manage.py migrate# Creating table structure
-Perform various operations on data in a database table based on a class
#添加一条记录
#方法一
Models. UserInfo.objects.create (username= ' root ', password= ' root ')
#方法二
Obj=models. UserInfo (username= ' Root2 ', password= ' Root2 ')
Obj.save ()
#方法三
dic={' username ': ' root3 ', ' Password ': ' Root3 '}
Models. UserInfo.objects.create (**dic)
field data type
Booleanfield (Field)
-Boolean value type
Nullbooleanfield (Field):
-A Boolean value that can be empty
Charfield (Field)
-Character type
-the Max_length parameter must be supplied, max_length indicates the character length
TextField (Field)
-Text Type
Emailfield (Charfield):
-String types, Django admin, and modelform provide validation mechanisms
Genericipaddressfield (Field)
-String types, Django Admin and Modelform provide validation Ipv4 and Ipv6
Parameters
protocol, for specifying Ipv4 or Ipv6, ' both ', ' IPv4 ', ' IPv6 '
Unpack_ipv4, if specified as true, enter:: ffff:192.0.2.1 time, 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)
-String types, Django Admin and Modelform provide validation support letters, numbers, underscores, connectors (minus signs)
Commaseparatedintegerfield (Charfield)
-string type, the format must be comma-separated number
Uuidfield (Field)
-String type, Django admin and Modelform provide validation of UUID format
Filepathfield (Field)
-Strings, Django Admin and Modelform provide the ability to read files in folders
Parameters
Path, Folder path
Match=none, regular match
Recursive=false, recursively the following folder
Allow_files=true, allow file
Allow_folders=false, allow folder
Filefield (Field)
-String, the path is saved in the database, the file is uploaded to the specified directory
Parameters
upload_to = "" Save path of upload file
Storage = None Storage component, default Django.core.files.storage.FileSystemStorage
ImageField (Filefield)
-String, the path is saved in the database, the file is uploaded to the specified directory
Parameters
upload_to = "" Save path of upload 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 image saved 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 to get the value of Datetime.timedelta type
Floatfield (Field)
-Floating-point type
Decimalfield (Field)
-10 Decimal
Parameters
Max_digits, fractional total length
decimal_places, decimal length
Binaryfield (Field)
-Binary type
Field parameters
Null=true whether a field in the database can be empty
Column names for fields in the Db_column database
Db_tablespace
Default values for fields in the default database
Primary_key whether a field in a database is a primary key
Db_index whether a field in the database can be indexed
Whether a field in a unique database can establish a unique index
Unique_for_date whether a unique index can be established in the field "date" section of the database
Whether a unique index can be established in the field "month" section of the Unique_for_month database
Whether a unique index can be established in the field "year" section of the Unique_for_year database
Auto_now_add the date and time that the record was added to the database
Update the date-time specific query Update method for the current record in the Auto_now database
--Obj=usergroup.objects.filter (id=1). First ()
obj.caption= ' xxx '
Obj.save
Field names displayed in the Verbose_name admin
Blank admin allows user input to be empty
Whether you can edit in editable admin
Help_text admin in the field of the prompt information
Choices Admin Displays the contents of the selection box, with unchanged data in memory to avoid cross-table operations
such as: GF = models. Integerfield (choices=[(0, ' ho Sui '), (1, ' big Cousin '),],default=1)
Error_messages custom error messages (dictionary types) to customize the error messages you want to display;
Dictionary health: null, blank, invalid, Invalid_choice, unique, and unique_for_date
such as: {' null ': ' cannot be empty. ', ' invalid ': ' Malformed '}
Validators Custom Error validation (list type) to customize the desired validation rules
From django.core.validators import Regexvalidator
From django.core.validators import emailvalidator,urlvalidator,decimalvalidator,\
Maxlengthvalidator,minlengthvalidator,maxvaluevalidator,minvaluevalidator
Such as:
Test = models. Charfield (
MAX_LENGTH=32,
error_messages={
' C1 ': ' Priority error message 1 ',
' C2 ': ' Priority error message 2 ',
' C3 ': ' Priority error message 3 ',
},
validators=[
Regexvalidator (regex= ' root_\d+ ', message= ' wrong ', code= ' C1 '),
Regexvalidator (regex= ' root_112233\d+ ', message= ' again wrong ', code= ' C2 '),
Emailvalidator (message= ' again wrong ', Code= ' C3 '),]
)
Python 105th Day---Django basics