Click on Django Skip to reading point
Download website
https://www.python.org/downloads/windows/
Django It was developed in a fast-paced newsroom environment , So it aims to make common Web Development tasks become fast and simple
stay Windows Installation on Python 3.8 and Django3.2.10
decompression Django To the folder , After entering the unzipped Directory , stay cmd Run in python setup.py install
Wait for the operation to finish ,cmd Test success
>python
Python 3.8.7
>>> import django
>>> django.get_version()
'3.2.10'
>>>
MVC representative Model-View-Controller ( Model - View - controller ) Pattern .
The core logic code jumps to V in
MTV representative Model-Template-View( Model - Templates - View ) Pattern .
Apply to Django The project is an independent business module ,
You can include your own route , View , Templates , Model
name
name
, … , …]├─name ''' Small MTV structure '''
│ │ admin.py # management
│ │ apps.py
│ │ models.py # Database correlation
│ │ tests.py
│ │ views.py # View logic
│ │ __init__.py
│ │
│ └─migrations # database
│ __init__.py
Django in ,
Main route profile (urls.py) Sure Do not handle user specific routes
,
The main route configuration file can Make the distribution of requests
( Distributed request processing ).
Specific requests can be handled by their respective applications
Create in app URLS
1 Call in main route include function , be used for
Transfer the current route to the routing profile of each application urlpatterns Distributed processing
include('app name .url Module name ')
for example :
path('music/',include(music.urls)),
2 setting Add an application to ( It's just adding a directory )
for example :
INSTALLED_APPS = [
'django.contrib.staticfiles',
'music',] # Otherwise, the template under the directory may not be found
3 Configure in app urls.py
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('index',views.index_view)
]
The template directory can be configured inside the application
'APP_DIRS' The value is True
that will do TEMPLATES = [
{
'APP_DIRS': True, }]
The model layer , Interacting with the database
What is a model ?
The model is a model Python class , It is from django.db.models.Model Derived subclasses .
- One
Model class
Represents the... In the databaseA data sheet
- In model class
Every class attribute
All represent... In the databaseA field
.- Model is the interface of data interaction , yes
Methods and ways of representing and operating databases
ORM (Object Relational Mapping) Object relation mapping ,
It is ― A programming technique ,
It allows you to operate on the database using classes and objects , So as to avoid passing through SQL Statement operation database
Establish correspondence between model classes and tables
, allow Operate the database in an object-oriented way
. You can switch databases with simple configuration
. advantage :
Only object-oriented programming is needed , No need to write code for database .
Operations on databases are translated into operations on class properties and methods .
No need to write various databases sql sentence .
Realize the decoupling of data model and database , It shields the differences in the operation of different databases .
Instead of paying attention, use mysql、oracle... And other internal details of the database .
Simple configuration makes it easy to change databases . Without changing the code
shortcoming :
For complex business , High use cost
Convert to SQL sentence , Convert to object according to the result of query , Performance loss during mapping .
The mapping relationship
class Model class name (mode1s.Mode1) :
Field name = models. Field type ( Field options )
1. establish app
python manage.py startapp bookstore
2. Write model models.py
'''from django.db import models class Book(models.Model): title = models.charFie1d(" Title ",max_length=50,default=' ') price = models.DecimalFie1d(' pricing ',max_digits=7,decimal_places=2,defau1t=0.0) '''
3. Database migration
Django Synchronize changes to the model ( Add fields , Delete model, etc ) To the database schema
(1) Generate migration file - perform
# python manage.py makemigrations
Apply the models.py File generates an intermediate file , And keep it in migrations In the folder
(2) Execute the migration script - perform
# python manage.py migrate
Execute the migration program to realize the migration . Apply the migrations The intermediate files in the directory are synchronized back to the database
# Many tables will be generated
Use the inside Meta Class to
Assign attributes to the model
,Meta There are many built-in classes under the class , You can do some control over the model class
class Book(models.Model):
...
...
class Meta:
db_table='name?'
...
Modify the table structure in models.py
Revision in China
Any changes to the table structure , Be sure to modify... On the corresponding model class
After modification
python manage.py makemigrations python manage.py migrate
- 1. Templates can be dynamically changed according to dictionary data html Webpage
- 2. The template can dynamically generate the corresponding dictionary data according to the dictionary data passed in the view HTML Webpage .
1. Create template folder < Project name >/templates
2. stay settings.py in TEMPLATES Configuration item
If the compiler cannot find the template
- BACKEND: Specify the engine for the template
- Accept view , Call the implementation of the view , The default system comes with
- DIRS: Search directory for templates
- Add the template directory you created ( It can be one or more )
- APP_DIRS∶ Whether to use in the application templates Search for template files in folders
- OPTIONS∶ Options for templates
The configuration item needs to be modified
Set up DIRS
- 'DIRS'": [os.path.join(BASE_DIR, 'templates')],
#template_view
from django.template import loader
#1. adopt 1oader Load template ‘
t = loader. get_template(" Template file name ") # Such as test.html
# 2. take t convert to HTML character string
html = t.render( Dictionary data )
# 3. Use the response object to return the converted String content to the browser
return HttpResponse(htm1)
''' from django.shortcuts import render return render(request,"test.html",dict) # request , Webpage , Dictionaries '''
#templates/test.html
<-- It can be used {
{ Variable name }} To reference the dictionary value passed in by the template /-->
<!DOCTYPE html>
<html lang="zh-Hans">
<head> </head>
<body>
<h1> This is the template </h1>
</body>
</html>
def mode_view(request):
dict={
"fruit":"apple",
"value":'10'
}
return render(request,"test1.html",dict)
Delivery type
str int list tuple dict func odj
{
{
name}}#( Variable name )
{
{
name.index}}
{
{
name.key}}
{
{
name. Method }}
{
{
Function name }}
effect
Tag syntax
if label
{% if expression 1 %}
...
{% elif expression 2 %}
...
{% else expression 3 %}
...
{% endif %}
for label
{% for name in list %}
{
{name}}
{% endfor %}
Template inheritance can reuse the content of the parent template , The child template directly inherits all the contents of the parent template and can overwrite the corresponding blocks in the parent template
# grammar – In the parent template :
Define blocks in the parent template block The tag identifies which sub modules are allowed to be modified
block label : Define... In the parent template , You can override... In a sub template
block What is not on the label cannot be changed
# grammar – In the sub template :
Inherit templates extends label ( Write in the first line of the template file )
for example {
%extends 'base.html'%}
The child template overrides the content block in the parent template
### block label ###
{
% block block_name %}
The child template plate is used to cover the parent template block_name Block content
{
% endblock block_name %}
Configure the access path to the static file 【 This configuration exists by default 】
# Through which url Address to find static file
STATIC_URL = '/static/'
explain :
Specifies that static files need to be accessed through /static/xxx
or http://127.0.0.1:8000/static/xxx
[xxx Represents the specific static resource location ]
# Configure the storage path of static files STATICFILES DIRS
STATICFILES_DIRS What is saved is the storage location of static files on the server side
STATICFILES_DIRS = (
os.path.join(BASE_DIR,"static"),
)
Accessing static files in templates
- img For example, labels
1.<img src=" /static/image/django2.jpg" width="200px"height="200px">
<img src="http://127.0.0.1:8000/static/image/django2.jpg">
2. adopt {%static %} Tag access to static files
load static -
# Top
{% load static %}
Use static resources – {% static ' Static resource path '%}
Examples
<img src="{% static 'images/lena.jpg'%}">
<body >
The basic operations include adding, deleting, modifying and checking , namely (CRUD operation )
CRUD It refers to the increase in the calculation process (Create)、 Read query (Read)、 to update (Update) And delete (Delete)
ORM CRUD The core —>Model class . Manager object (model.object. )
Each inherits from models.Model Model class of , There will be one objects Objects are also inherited .
This object is called the manager object , The addition, deletion, modification and query of the database can be realized through the model manager
open mysite/settings.py
. It's an inclusion of Django Project settings Python modular .
Django There are two ways to configure a database
Method 1 : Directly in settings.py Add database configuration information to the file
DATABASES = {
# Method 1
'default': {
'ENGINE': 'django.db.backends.mysql', # Database engine
'NAME': 'mysite', # Database name
'USER': 'xiaohong', # Database login user name
'PASSWORD': 'xiaohong', # password
'HOST': '127.0.0.1', # Database host IP
'PORT': 3306, # Database port number
}
}
`'django.db.backends.sqlite3'`
`'django.db.backends.postgresql'`
`'django.db.backends.mysql'`
`'django.db.backends.oracle'`
Direct use makes mistakes
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.
Did you install mysqlclient?
Installation package
pip install pymysql
To be in settings.py In the package where the file is located __init__.py
Import pymysql
import pymysql
pymysql.install_as_MySQLdb()
How to use it · Model USES
Method 2 : Save the database configuration information to a file , stay settings.py File will be introduced into .( recommend )
New database profile my.cnf( Choose your name )
[client]
database = blog
user = blog
password = blog
host =127.0.0.1
port = 3306
default-character-set = utf8
stay settings.py Introduce in the file my.cnf file
DATABASES = {
# Method 2 :
'default': {
'ENGINE': 'django.db.backends.mysql',
'OPTIONS': {
'read_default_file': 'utils/dbs/my.cnf',
},
}
}
BooleanField()
Database type :tinyint(1) -- In programming language : Use true or False To represent a value
In the database : Use 1 or 0 To represent specific values
CharField()
Database type :varchar
Be careful : Must specify max_length Parameter values
DateField()
Database type :date Indicates the date √ Parameters :
auto_now: Every time you save an object , Automatically sets this field to the current time ( Value :True/False)
acto_now_add: The current time is automatically set when the object is first created ( Value :True/False)
default: Set the current time ( Value : String format time, such as : '2019-6-1').
Only one of the above three parameters can be selected
DateTimeField()
Database type :datetime(6) Indicates that the date and time parameters are the same as DateField
FloatField()
Database type :double
Decimal values are used in programming languages and databases
DecimalField()
Database type :decimal(x,y)
In programming language : Use decimal to represent the value of the column √ In the database : Use decimals
Parameters :
max_digits: Total number of digits , Including the number of digits after the decimal point . The value must be greater than or equal to decimal_places.
decimal_places: The number of digits after the decimal point
EmailField()
Database type :varchar
Using strings in programming languages and databases
IntegerField()
Database type :int
Use integers in programming languages and databases
lmageField()
Database type varchar(100)
effect : In order to save the path of the picture in the database
Using strings in programming languages and databases
TextField()
Database type :longtext
effect : Represents character data of variable length
Field options , Specify additional information for the created column
primary_key
If set to True, Indicates that the column is the primary key , If you specify a field as the primary key , The database table will not be created id Field
blank ( And null Different )
Set to True when , Field can be empty . Set to False when , Fields are required
null
If set to True, Indicates that the column value is allowed to be empty .
The default is False, If this option is False, It is suggested to join default Option to set the default values
default
Set the default value of the column , If field options null=False It is recommended to add this item
db_index
If set to True, Add index to the column
unique
If set to True, Indicates that the value of the field in the database must be unique ( It can't be repeated )
db_column
Specify the name of the column , If not specified, the attribute name is used as the column name
verbose_name
Set this field in admin The display name on the interface
# Create a property , Represents the user name , length 30 Characters , Must be unique , Can't be empty , Add index
name = models.charField(max_length=30,unique=True,nu77=False,db_index=True)
In a relational database , Usually not all the data will be put in the same table , Not easy to expand ,
Common relationship mappings are :
Table relations
One-to-one mapping
OneToOneField( Class name , on_delete=xxx)
class B(mode1 .Mode1) :
attribute = models.oneTooneFie1d( class A,on_delete=??)
How to delete
1.models.CASCADF cascading deletion .
Django simulation SQL constraint ON DELETECASCADE act , And delete the containing ForeignKey The object of .
2.models.PROTECT Throw out ProtectedError To prevent the deletion of the referenced object ;
[ Equate to mysql default RESTRICT]
3.SET_NULL Set up ForeignKey null;
You need to specify the null=True
4.SET_DEFAULT take ForeignKey Set as its default ;
You have to set ForeignKey The default value of .
# Create data
Model classes with foreign keys
wife1 = Wife.objects.create(name=' Mrs. Wang ', author=author1)
# Mr. Wang obj
wife1 = Wife.objects.create(name=' Mrs. Wang ';author_id=1)
# The primary key value corresponding to Mr. Wang
# Inquire about
# Is the query : Pass the foreign key attribute query directly , It is called forward query
wife = wife.objects.get(name=' Mrs. Wang ')
print(wife.name,' My husband is ',wife.author.name)
# Reverse query - The party without foreign key properties , You can call the reverse attribute to query the other associated party
The reverse association attribute is ` Instance object . Reference class name ( A lowercase letter ),
- When the back reference does not exist , An exception is triggered
author1 = Author.objects.get(name=' Teacher wang ')
author1.wife.name
One to many mapping
One to many is the one to many correspondence between real things .
# One to many needs to identify specific roles , Set foreign keys on multiple tables
When one A Class objects can be associated with multiple B When the class object
class A(mode1 . Mode1): One
class B (model.Mode1):
attribute = mode1s.ForeignKey(" One " Model class of ,on_delete=xx)
# Create data
from .models import *
pub1= Publisher.objects.create(name=' tsinghua ')
Book.objects.create(title='C++', publisher=pub1)
Book.objects.create(title='Java', publisher_id=1)
# Inquire about A:B=1: many
class B obj. Foreign key properties .A attribute
class A obj. class B_set.all()
Many to many mapping
Many to many represents many to many complex relationships between objects , Such as : Everyone has a different school ( Primary school , Junior high school , high school ...), Every school has different students ...
mysql You need to rely on the third table to create many to many in
Django There is no need to manually create a third table ,Django Done automatically
# grammar : In either of the two associated classes ,
B Attribute added = models.ManyToManyField(A)
# Create data
First create book Again author
book = Book.objects.create(title= ' python1 ' )
author3 = book.authors.create(name= ' guoxiaonao ' )
book.authors.add(author1)
# Forward query objects with many to many attributes to the other party
adopt Book Query all the corresponding Author
At this point, many to many attributes are equivalent to objects
book.authors.a11() -> obtain book All the corresponding author Information about
book.authors.filter(age_gt=80) -> obtain book The corresponding authors are older than 80 Information about the author
# Reverse query
adopt Author Query all the corresponding Book Use the reverse attribute book_set
author.book_set.all()
author.book_set.filter()
To create each record in the data is to create a data object scheme 1
1.
MyModel.objects.create( attribute 1= value 1, attribute 2= value 1..)
success : Returns the created entity object
Failure : Throw an exception
2. establish MyModel Instance object , And call save() Preservation
obj = MyMode1( attribute = value , attribute = value )
obj. attribute = value
obj.save()
stay Django Provides an interactive operation project called Django Shell
It can perform corresponding operations with the code of the project in interactive mode
utilize Django Shell Instead of writing view Code for direct operation
Be careful : When the project code changes , Re enter Django
shell Starting mode :
python manage.py shell
>>> from bookstore.models import Book
>>> b1=Book.objects.create(title='zzl',price='endless')
>>> b2=Book(title="qqq",price="1100")
>>> b2.save()
mysql> select * from bookstore_book;
+----+-------+---------+
| id | title | price |
+----+-------+---------+
| 1 | zzl | endless |
| 2 | qqq | 1100 |
+----+-------+---------+
The query of the database needs to be performed using the manager object
adoptMyModel.objects Manager
Method calls the query method
Simple query
MyModel.objects.all()
Search all records , return QuerySet Query object , [obj,obj2...]
def __str__(self):
retrun Display format
Query only some fields
MyModel.objects.values( Field 1, Field 2...)# Using class attributes , In fact, it operates on database fields
return [{
},{
}]
MyModel.objects.values_list( Field 1, Field 2...)
return [(),(),]
MyModel.objects.values( Field 1, Field 2...).order_by( Field 1, Field 2...)
return [obj,obj2...]
Conditions of the query
# Equality query
MyModel.objects.get( attribute = value 1,..2,..3)
Query the unique records that meet the conditions , If not 1 Data , error
return obj
MyModel.objects.filter( attribute = value 1,..2,..3)
Query multiple records that meet all conditions
return [obj,...]
MyModel.objects.exclude( attribute = value 1,..2,..3)
Query all unqualified records
return [obj,...]
# Non equality query
query predicate
Definition : When making more flexible conditional queries, you need to use query predicates
explain : Each query predicate is an independent query function
_exact: Equivalence match
_contains : Contains the specified value
_startswith : With XXX Start
_endswith : With XXX end
_gt : Greater than
_gte : Greater than or equal to
_it : Less than
_ite : Less than or equal to
_in : (?_in=[,,])
_range :(?_range(a,b))
MyModel.objects.filter( attribute _contains = value 1,..2,..3)
1. check
get(id=?)
2. Change
obj. attribute =?
3.save()
# Bulk changes
books = Book.objects.filter(id_gt=3)
books.update(price=O)
# Set the retail price of all books at 100 element
books = Book.objects.all()
1. Find data objects
2. To call this data object delete() Method to delete
try:
auth = Author.objects.get(id=1)
auth.delete()
except:
print( Delete failed )
F
One F Object represents the information function of the field of a record in the database :
It usually operates on the field values in the database without obtaining them - Used for class properties ( Field ) Comparison between .
from django . db .models import F
F(' Name ')
Book.objects.a11().update(market_price=F( 'market_price ')+10)
Mutually exclusive execution
Q
Used in conditions to achieve division and(&) Outside of the or() or not(~) Operation operator :
& And operation
| Or operation
&~ Non operational
from django. db.mode1s import Q
Q( Conditions 1)|Q( Conditions 2) # Conditions 1 Establishment or condition 2 establish
Q( Conditions 1)&Q( Conditions 2) # Conditions 1 And conditions 2 Simultaneous establishment
Q( Conditions 1)&~Q( Conditions 2) # Conditions 1 Established and conditional 2 Don't set up
book.objects.filter( Q()|Q() )
Aggregate queries are
Perform partial or full statistical query on the data of a field in a data table
,check bookstore_book The average price of all the books in the data sheet ,
Check the total number of all books, etc , Use aggregate queries
Aggregate queries are divided into
The import method : from django.db.models import *
Aggregate functions : Sum, Avg,Count,Max,Min
grammar :MyModel.objects.aggregate( Result variable name = Aggregate functions (' Column '))
- Return results : A dictionary of result variable names and values
The format is :{
Result variable name ": value }
Grouping aggregation refers to the collection of objects associated with each object in the query results ,
So we can get the total value ( It can also be an average or a sum ), Aggregate is generated for each item in the query set .
grammar :
- QuerySet.annotate( Result variable name = Aggregate functions (' Column '))
Return value :
QuerySet
Group first
bs = Book.objects.values ( ' pub')
bs.annotate(res=Count( 'id' ) )
>>> <QuerySet [{
'pub': ' tsinghua university press ','res': 2},{
'pub': ‘ Mechanical industry press
bs.annotate(res=Count( 'id' ) ).filter(res_gt=1)
Django It can also support the direct use of sql Statement to communicate with the database
Inquire about :
Use MyModel.objects.raw() Perform database query operation
grammar :
MyModel.objects.raw(sql sentence , Splicing parameter )
Return value :
RawQuerySet A collection of objects 【 Only basic operations are supported , For example, circulation 】
Operate the database completely across model classes - Inquire about / to update / Delete
1. Import cursor The bag where it is
from django.db import connection
⒉ Create... With cursor Class constructor creation cursor object , Reuse cursor object ,To ensure that... Can be released in case of exception cursor resources , Usually use with Statement to create
from django.db import connection
with connection.cursor() as cur:
cur.execute(' perform sQL sentence ',' Splicing parameter ')
open mysite/settings.py
. It's an inclusion of Django Project settings Python modular .
Django There are two ways to configure a database
Method 1 : Directly in settings.py Add database configuration information to the file
DATABASES = {
# Method 1
'default': {
'ENGINE': 'django.db.backends.mysql', # Database engine
'NAME': 'mysite', # Database name
'USER': 'xiaohong', # Database login user name
'PASSWORD': 'xiaohong', # password
'HOST': '127.0.0.1', # Database host IP
'PORT': 3306, # Database port number
}
}
`'django.db.backends.sqlite3'`
`'django.db.backends.postgresql'`
`'django.db.backends.mysql'`
`'django.db.backends.oracle'`
Direct use makes mistakes
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.
Did you install mysqlclient?
Installation package
pip install pymysql
To be in settings.py In the package where the file is located __init__.py
Import pymysql
import pymysql
pymysql.install_as_MySQLdb()
How to use it · Model USES
Method 2 : Save the database configuration information to a file , stay settings.py File will be introduced into .( recommend )
New database profile my.cnf( Choose your name )
[client]
database = blog
user = blog
password = blog
host =127.0.0.1
port = 3306
default-character-set = utf8
stay settings.py Introduce in the file my.cnf file
DATABASES = {
# Method 2 :
'default': {
'ENGINE': 'django.db.backends.mysql',
'OPTIONS': {
'read_default_file': 'utils/dbs/my.cnf',
},
}
}
BooleanField()
Database type :tinyint(1) -- In programming language : Use true or False To represent a value
In the database : Use 1 or 0 To represent specific values
CharField()
Database type :varchar
Be careful : Must specify max_length Parameter values
DateField()
Database type :date Indicates the date √ Parameters :
auto_now: Every time you save an object , Automatically sets this field to the current time ( Value :True/False)
acto_now_add: The current time is automatically set when the object is first created ( Value :True/False)
default: Set the current time ( Value : String format time, such as : '2019-6-1').
Only one of the above three parameters can be selected
DateTimeField()
Database type :datetime(6) Indicates that the date and time parameters are the same as DateField
FloatField()
Database type :double
Decimal values are used in programming languages and databases
DecimalField()
Database type :decimal(x,y)
In programming language : Use decimal to represent the value of the column √ In the database : Use decimals
Parameters :
max_digits: Total number of digits , Including the number of digits after the decimal point . The value must be greater than or equal to decimal_places.
decimal_places: The number of digits after the decimal point
EmailField()
Database type :varchar
Using strings in programming languages and databases
IntegerField()
Database type :int
Use integers in programming languages and databases
lmageField()
Database type varchar(100)
effect : In order to save the path of the picture in the database
Using strings in programming languages and databases
TextField()
Database type :longtext
effect : Represents character data of variable length
Field options , Specify additional information for the created column
primary_key
If set to True, Indicates that the column is the primary key , If you specify a field as the primary key , The database table will not be created id Field
blank ( And null Different )
Set to True when , Field can be empty . Set to False when , Fields are required
null
If set to True, Indicates that the column value is allowed to be empty .
The default is False, If this option is False, It is suggested to join default Option to set the default values
default
Set the default value of the column , If field options null=False It is recommended to add this item
db_index
If set to True, Add index to the column
unique
If set to True, Indicates that the value of the field in the database must be unique ( It can't be repeated )
db_column
Specify the name of the column , If not specified, the attribute name is used as the column name
verbose_name
Set this field in admin The display name on the interface
# Create a property , Represents the user name , length 30 Characters , Must be unique , Can't be empty , Add index
name = models.charField(max_length=30,unique=True,nu77=False,db_index=True)
In a relational database , Usually not all the data will be put in the same table , Not easy to expand ,
Common relationship mappings are :
Table relations
One-to-one mapping
OneToOneField( Class name , on_delete=xxx)
class B(mode1 .Mode1) :
attribute = models.oneTooneFie1d( class A,on_delete=??)
How to delete
1.models.CASCADF cascading deletion .
Django simulation SQL constraint ON DELETECASCADE act , And delete the containing ForeignKey The object of .
2.models.PROTECT Throw out ProtectedError To prevent the deletion of the referenced object ;
[ Equate to mysql default RESTRICT]
3.SET_NULL Set up ForeignKey null;
You need to specify the null=True
4.SET_DEFAULT take ForeignKey Set as its default ;
You have to set ForeignKey The default value of .
# Create data
Model classes with foreign keys
wife1 = Wife.objects.create(name=' Mrs. Wang ', author=author1)
# Mr. Wang obj
wife1 = Wife.objects.create(name=' Mrs. Wang ';author_id=1)
# The primary key value corresponding to Mr. Wang
# Inquire about
# Is the query : Pass the foreign key attribute query directly , It is called forward query
wife = wife.objects.get(name=' Mrs. Wang ')
print(wife.name,' My husband is ',wife.author.name)
# Reverse query - The party without foreign key properties , You can call the reverse attribute to query the other associated party
The reverse association attribute is ` Instance object . Reference class name ( A lowercase letter ),
- When the back reference does not exist , An exception is triggered
author1 = Author.objects.get(name=' Teacher wang ')
author1.wife.name
One to many mapping
One to many is the one to many correspondence between real things .
# One to many needs to identify specific roles , Set foreign keys on multiple tables
When one A Class objects can be associated with multiple B When the class object
class A(mode1 . Mode1): One
class B (model.Mode1):
attribute = mode1s.ForeignKey(" One " Model class of ,on_delete=xx)
# Create data
from .models import *
pub1= Publisher.objects.create(name=' tsinghua ')
Book.objects.create(title='C++', publisher=pub1)
Book.objects.create(title='Java', publisher_id=1)
# Inquire about A:B=1: many
class B obj. Foreign key properties .A attribute
class A obj. class B_set.all()
Many to many mapping
Many to many represents many to many complex relationships between objects , Such as : Everyone has a different school ( Primary school , Junior high school , high school ...), Every school has different students ...
mysql You need to rely on the third table to create many to many in
Django There is no need to manually create a third table ,Django Done automatically
# grammar : In either of the two associated classes ,
B Attribute added = models.ManyToManyField(A)
# Create data
First create book Again author
book = Book.objects.create(title= ' python1 ' )
author3 = book.authors.create(name= ' guoxiaonao ' )
book.authors.add(author1)
# Forward query objects with many to many attributes to the other party
adopt Book Query all the corresponding Author
At this point, many to many attributes are equivalent to objects
book.authors.a11() -> obtain book All the corresponding author Information about
book.authors.filter(age_gt=80) -> obtain book The corresponding authors are older than 80 Information about the author
# Reverse query
adopt Author Query all the corresponding Book Use the reverse attribute book_set
author.book_set.all()
author.book_set.filter()
>django-admin startproject mysite1
# Create a directory structure
''' mysite1/ manage.py mysite1/ __init__.py settings.py urls.py asgi.py wsgi.py '''
setting.py
route , and manage.py
route
Into the outer layer mysite
In the case of catalogues , Please switch to this directory , Then run the following command :
$ python manage.py runserver (ip:port)
visit http://127.0.0.1:8000/ See the success interface
// Launched the Django Built in simple server for development , It is a pure Python Write lightweight Web The server .
This server is built in Django Is to enable you to quickly develop what you want ,
project VS application
What is the difference between project and Application ? An application is a web application that specializes in doing something —— Like the blog system , Or a database of public records , Or a small voting process . Project is a collection of configuration and application used by a website . The project can contain many applications . Applications can be used by many projects .
stay Django in , Every app is Python package , And follow the same Convention .Django Bring a tool with you , It can help generate the basic directory structure of the application
manage.py
Create a voting application under the same level directory . So it can be imported as a top-level module , Not and mysite
Sub module of .python manage.py startapp polls
''' This structure directory contains all the contents of the voting application . polls/ __init__.py admin.py apps.py migrations/ __init__.py models.py tests.py views.py '''
Get into polls/view.py, Write view
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
This is a Django The simplest view in .
In order to create URLconf, stay polls Create a new one in the directory urls.py
stay polls/urls.py
in , Enter the following code :
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
The next step is to root URLconf The file specifies the polls.urls
modular .
stay mysite/urls.py
Inside the file urlpatterns
Insert a include()
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
function include()
Allow reference to other URLconfs. Delete Django encounter include()
when , It truncates the that match the insert URL Part of , Send the script string to URLconf For further processing .
stay Django Write a database driven Web The first step in the application is to define the model - That is, database structure design and additional metadata
Design philosophy
# A model is a single source of information that defines your data .
# The model contains indispensable data areas and your behavior of storing data .
# Django follow DRY principle . The purpose is to define that your data model should be in one place , And automatically deduce something from that position .
Let's introduce the migration - for instance , Unlike Ruby On Rails,Django The migration code of is generated automatically by your model file , It is essentially a historical record ,Django It can be used for rolling update of database , In this way, it can be matched with the current model .
Voting Application , You need to create two models : problem Question
And options Choice
.
Question
The model includes problem description and release time .Choice
The model has two fields , Option description and current votes . Each option is a problem . edit polls/models.py
file :
from django.db import models
# Every model django.db.models.Model There are many class variables ,
# --> They all represent a database field in the model .
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
# Almost all fields Field Example
# The character field is represented as CharField,
# The date time field is represented as DateTimeField.
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
# Definition section Field Class instance requires parameters .
# for example CharField Need one max_length Parameters . This parameter is used to define the database structure , Also used to validate data , We will see this soon .
# Field It can also receive several optional parameters ; In the example above : We will votes Of default Which is the default value , Set to 0.
# We use ForeignKey Defines a relationship .
This will tell Django, Every Choice Objects are associated with a Question object .Django Support all common database relationships : For one more 、 Many to many and one to one .
Django You can do this by creating the code for the model :
CREATE TABLE
Question
and Choice
Objects interact Python database API But first of all, we should polls
Install the application into our project .
# Design philosophy
Django The application is “ Pluggable ” Of . You can use the same... In multiple projects . besides , You can also publish your own apps , Because they will not be bound to the currently installed Django On .
INSTALLED_APPS
Add settings . because PollsConfig
Class is written in the file polls/apps.py
in , So its path is 'polls.apps.PollsConfig'
site/setting.py
INSTALLED_APPS = [
'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
site/polls/app.py
from django.apps import AppConfig
class PollsConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'polls'
Now? Django The project will contain polls
Applications . Run the following command :
$ python manage.py makemigrations polls
Access a web site from an open browser , End this visit by closing the browser , Call it a conversation
HTTP Protocol is stateless , This makes it difficult to maintain the session state
Cookies Storage space saved on the client browser
Chrome Browser through the developer tools Application >>Storage >>
Cookies
View and operate all the on the browser side Cookies value
Firefox may be stored through developer tools -> Cookie see
1.cookies On the browser, click - Stored as a value pair ,
Both keys and values are in the form of ASCII Shape storage of string ( Cannot be a Chinese string )
2. Stored data has a lifecycle
3.cookies The data in is stored and isolated by domain , Cannot access between different domains
4.cookies The internal data will be carried to the server every time you visit this website , If cookies Too much will reduce the response speed
Server response Cookie Set up
HttpResponse.set_cookie(key, value=", max_age=None,expires=None)
- key:cookie Name
- value:cookie Value
- max_age:cookie Survival time , Seconds per unit
- expires: Specific expiration time
- When you don't specify max age and expires when , This data is invalid when the browser is closed
resp = HttpResponse( 'set cookies is ok' )
resp.set_cookie( ' uuname ' , 'gxn' ,500)
# add to cookie, modify cookie
# Add keys to the browser my_var1, The value is 123, The expiration date is 1 Hour cookie
responds = HttpResponse(" Have been added my_var1, The value is 123")
responds.set_cookie( 'my_var1',123,3600)
return responds
# Delete Cookies
- HttpResponse.delete_cookie(key)
- Delete specified key Of Cookie. If key Nothing happens if it doesn't exist
# obtain Cookies
- adopt request.COOKIES Bound Dictionary (dict)
# Get client's COOKIES data
value = request.COOKIES.get('cookies name ',' The default value is ')
Session Open up a space on the server to retain important data when the browser interacts with the server
Realization way
- Use session You need to start in the browser client cookie, And in cookie Storage in sessionid
- Each client can have an independent server on the server side Session
- Be careful : Different requesters will not share this data , One to one correspondence with the requester
To configure
settings.py Middle configuration session
1, towards INSTALLED_APPS Add... To the list :
INSTALLED_APPS = [
# Enable sessions application
'django.contrib.sessions ' ,
]
2, towards MIDDLEWARE Add... To the list :
MIDDLEWARE = [
# Enable session middleware
'django.contrib.sessions.middleware.sessionMiddleware'
]
Use
session For example, a dictionary like SessionStore Object of type ,
You can operate in a dictionary like manner
session Can store such as string , integer , Dictionaries , List etc. .
1, preservation session Value to server
request.session['KEY'] = VALUE
2, obtain session Value
value = request.session['KEY']
value = request.session.get('KEY', The default value is )
3, Delete session
del request.session['KEY"]
def set_session( request) :
request.session [ ' uname' ] = 'wwc'
return HttpResponse( ' set session is ok')
def get_session( request) :
value = request.session [ ' uname ' ]
return HttpResponse( 'session value is %s '%(valuel))
Use
settings.py Related configuration items in
1,SESSION_COOKJE_AGE
effect : Appoint sessionid stay cookies The length of time to save in ( The default is 2 Zhou ),
For example :SESSION_COOKIE_AGE = 60* 60 * 24*7* 2
2, SESSION_EXPIRE_AT_BROWSER_CLOSE= True
Set as long as the browser is closed ,session Is the failure ( The default is False)
Be careful :Django Medium session Data stored in database
, So use session You need to make sure that you have performed migrate
1, django_session Table is a single table design ;
And the data volume of this table continues to increase 【 The browser deliberately deleted sessionid& Expired data not deleted 】
2, Can be performed every night python3 manage.py clearsessions
【 This command deletes expired session data 】
django It provides a relatively perfect interface for background management database ,
For use in invocation and testing.
django All registered model classes will be collected ,
Arch data management interface for these model classes , For developers
Create background management account – This account is the highest authority account in the management background
$ python3 manage.py createsuperuser
Function has path()
Four parameters , Two required parameters :route
and view
, Two optional parameters :kwargs
and name
.
route
It's a match URL Principle of ( Like regular expressions ). When Django In response to a request , It will be from urlpatterns
The first item starts , Arrange the items in the matching list in order , Until a match is found .These features will not match GET and POST Parameter or domain name . for example ,URLconf Processing requests requests
https://www.example.com/myapp/
when , It will try to matchmyapp/
. Processing requestshttps://www.example.com/myapp/?page=3
when , You can also try to matchmyapp/
When Jiange finds a matching model , The specific view will be called , And call a HttpRequest
Object first parameter , By “ As ” The parameters of parameters are presented in the form of keyword parameters .
kwargs Any keyword parameter can be passed to the target view function as a dictionary .
name For you URL Name can let you in Django The only place that references it , In particular, special features in templates allow you to modify only one file externally URL Pattern .
**render()** The grammar is as follows :
def render(request, template_name, context=None, content_type=None,
status=None, using=None)
render Parameters of request and template name Is the required parameter , The remaining parameters are optional . The parameters are described as follows .
Django Provided in HttpResponseRedirect Object to implement redirection , This class inherits from HttpResponse, Is defined in django.http Module , The status code returned is 302.
Absolute address
http://127.0.0.1:8000/page/12,
Relative address
'/page/1'
‘/’ Relative address at the beginning ,
The browser will send the protocol in the current address bar ,ip And port plus this address , As the final access address ,
That is, if the address bar of the current page is http://127.0.0.1:8000/page/3; The final result of the current relative address is http://127.0.0.1:8000 + /page/1
'page/1’
No, ‘/ Relative address at the beginning ,
The browser will be based on the current url The last / Add the relative address to the previous content as the final access address ,
For example, the current address bar address is http://127.0.0.1:8000/topic/detail; Then the final result of the relative address is http://127.0.0.1:8000/topic/ + page/1
url Reverse parsing refers to the use of the in a view or template ,
use path Define the name to dynamically find or calculate the corresponding route
path Syntax of functions
path(route, views, name=" Alias ")
path(page', views.page_view, name="page_url")
according to path Medium `name=` Pass the keyword to url Identified a unique name
In a template or view , You can infer this from the name url Information
Use in templates url The label realizes the reverse resolution of the address
{
% url‘ Alias ’%}
{
% url ' Alias ’' Parameter values 1'' Parameter values 2’%}
{
% ur1 'pagen''400’%}
{
% url 'person' age='18' name=' gxn'%}
In the view function -> Callable django Medium reverse Method
from django.urls import reverse
url=reverse(' Alias ',args=[],kwargs={
})
URL Jump
url Jump also means call path Function views The view
url Jump form
1. adopt html Tag Links , Form links
2. adopt redict function
1.URL
path(r'<int>/<int>',a)
def a(request,item1,item2):
return HttpResponse()
get
- Request in Django in , Is the first parameter of the view function , namely HttpRequest object
- Django Received http Agreement after the request , It will be created according to the request data message HttpRequest object
- HttpRequest Object describes all the relevant information of the request through attributes
path_info: URL character string
method: character string , Express HTTP Request method , Common values :'GET'、'POST
GET: QueryDict Query dictionary objects , contain get All data in the request mode
POST: QueryDict Query dictionary objects , contain post All data in the request mode
FILES: A dictionary like object , Include all upload file information
COOKIES: Python Dictionaries , All inclusive cookie, Keys and values are strings
session: Dictionary like objects , Represents the current session
body: character string , Content of request body (POST or PUT)
scheme: Request protocol ('http' /'https')
request.get_full _path()∶ The full path of the request
request.META: Metadata in request ( The message header )
client IP Address -> request.META['REMOTE_ADDR'] :
# In the view function output
def test_request ( request) :
print( ' path info is' , request.path_info)
print ( ' method is', request.method)
print ( ' querystring is' , request.GET)
return HttpResponse( ' test request ok' )
Constructor format :
HttpResponse(content= Response body ,content_type= Response body data type , status= Status code )
effect :
Returns a response to the client browser , At the same time, carry the content of the response body
frequently-used Content-Type as follows
>
- 'text/html’( default ,html file )
- 'text/plain’( Pure text )
- 'text/css’(css file )
- 'text/javascript'(js file )
- 'multipart/form-data’( File submission )
- 'application/json'(json transmission )
- 'application/xml’(xml file )
GET
- Enter... In the browser address bar URL, After returning
- <a href=" Address ? Parameters = value & Parameters = value ">
- form In the form method by get
POST
The client uses forms and so on POST Request to pass the data to the server , Such as :
<form method=' post' action=" /login">
<input type="text" name="username">
<input type= 'submit' value=' land '>
</form>
Django Of get,POST Requests are responded to in the view function
def test_get_post( request) :
if request.method == 'GET" :
#request.GET Dictionaries
request.GET[' Parameter name ']
request.GET.get(' Parameters ',' The default value is ') # No parameters have default values , Don't go wrong
request.GET.getlist(' Parameters ') # Take all values
elif request.method == "'POST' :
request.POST[' Parameter name ']# request.PoST binding QueryDict
request.PoST.get(' Parameter name ','')
request.POST.getList(' Parameter name ')
# Cancel csrf verification , otherwise Django Will reject the message from the client POST request , newspaper 403 Respond to
''' Cancel csrf verification - Forbid to drop settings.py in MIDDLEWARE Medium CsrfViewsMiddleWare Middleware MIDDLEWARE = [ # Comment out ' django.middleware.csrf.csrfviewMiddleware ', ] '''
else:
pass
return HttpResponse( '--test get post is ok-- ' )
Besides , Look at the header of the file INSTALLED_APPS Set item . This includes all that will be enabled in your project Django application . The application can be used in multiple projects , You can also package and publish applications , Let others use it .
Usually , INSTALLED_APPS The default includes the following Django Built in application of :
django.contrib.admin -- Administrator site , You'll use it soon .
django.contrib.auth -- Authentication and authorization system .
django.contrib.contenttypes -- Content type framework .
django.contrib.sessions -- Conversational framework .
django.contrib.messages -- Message frame .
django.contrib.staticfiles -- Framework for managing static files .
These applications are enabled by default to facilitate regular projects .
Some applications opened by default need at least one data table , therefore , Before using them, you need to create some tables in the database . Execute the following command :
$ python manage.py migrate
# This migrate Command check INSTALLED_APPS Set up , Create the required data tables for each of these applications ,
As for what will be created , It depends on your mysite/settings.py Set up files and database migration files for each application ( We will introduce this later ). Each migration operation performed by this command will be displayed in the terminal . If you're interested , Run the command line tools for your database , And enter the \dt (PostgreSQL)、SHOW TABLES; (MariaDB,MySQL)、.schema (SQLite) perhaps SELECT TABLE_NAME FROM USER_TABLES; (Oracle) Let's see Django Which tables have been created
https://docs.djangoproject.com/zh-hans/3.2/topics/http/urls/
urls.py Of urlparttern Configure the corresponding view The function is written in view.py in
1. Routing configuration - path
path() function
Import from django.urls import path
grammar – path(route, views, name=None)
Parameters :
route: String type , Matching request path
views: Specifies the name of the view handler function corresponding to the path
name: Alias the address , When reverse address resolution is used in the template
2. Routing configuration - path - converter
#path converter
1· grammar :/< Converter type : Custom name >
2· effect : If the converter type matches the data of the corresponding type , Then the data is passed to the view function by keyword parameter transfer
3· Example : path('page/<int:page>', views.xxx)
# hold int Type variable page In the form of keyword parameter transfer To the view function view.XXX
Such as path('src/<int:value>',view.test)
view function
def test(request,value):# Add the second parameter value
return HttpResponse()
The following paths are valid by default :
str
- matching '/'
A non - empty string . If the expression does not contain a transformation , Default matching string .
int
- matching 0 Or any positive moment . Return to one int
.
slug
- Match any by ASCII A short label consisting of alphanumeric characters or hyphens and underscores building-your-1st-django-site
.
uuid
- Match a format UUID. To prevent multiple URL Map to a page , Must contain dashes and all characters are lowercase . for example ,075194d3-6885-417e-a8a8-6c931e272f00
. Return to one UUID
example .
path
- Match non airspace , Include a path prompt '/'
. It allows you to match complete URL, Not like it str
That matches URL Part of .
Register a custom path converter
For more complex matching requirements , You can define your own path converter .
The transformation is a class , It includes the following :
regex
Class properties .to_python(self, value)
Method , You can choose to process the matching string into the type of function . If not converted to the given value , It should trigger ValueError
.ValueError
Description: no match succeeded , So there is another URL Pattern matching succeeded , Otherwise, it will send to the user 404 Respond to .to_url
Method , transformation Python The type is a string used for URL in . If the given value cannot be converted , Can cause errorfor example :
class FourDigitYearConverter:
regex = '[0-9]{4}'
def to_python(self, value):
return int(value)
def to_url(self, value):
return '%04d' % value
stay URLconf Use in register_converter()
To register a custom transformation class :
from django.urls import path, register_converter
from . import converters, views
register_converter(converters.FourDigitYearConverter, 'yyyy')
urlpatterns = [
path('articles/2003/', views.special_case_2003),
path('articles/<yyyy:year>/', views.year_archive),
...
]
Using regular expressions
If the path and converter syntax are not sufficient to define your URL Pattern , You can also use regular expressions . So , Please use re_path()
Instead of path()
.
stay Python In regular expressions , The syntax for naming regular expression groups is (?P<name>pattern)
, among name
Is the name of the group and pattern
Some patterns to match .
urlpatterns[
# r'^ It's the beginning ,
# (?P<name>pattern) Match for groups , The number of digits can be limited
# $ For the end
re_path(r"^(?P<x>\d{
1,2})/( ?P<op>\w+)/( ?P<y>\d[1,2}$)',views.cal2_view)
// Be similar to
path( '<int:n>/<str:op=/<int:m>', views.cal_view) ,
]
- Request in Django in , Is the first parameter of the view function , namely HttpRequest object
- Django Received http Agreement after the request , It will be created according to the request data message HttpRequest object
- HttpRequest Object describes all the relevant information of the request through attributes
path_info: URL character string
method: character string , Express HTTP Request method , Common values :'GET'、'POST
GET: QueryDict Query dictionary objects , contain get All data in the request mode
POST: QueryDict Query dictionary objects , contain post All data in the request mode
FILES: A dictionary like object , Include all upload file information
COOKIES: Python Dictionaries , All inclusive cookie, Keys and values are strings
session: Dictionary like objects , Represents the current session
body: character string , Content of request body (POST or PUT)
scheme: Request protocol ('http' /'https')
request.get_full _path()∶ The full path of the request
request.META: Metadata in request ( The message header )
client IP Address -> request.META['REMOTE_ADDR'] :
# In the view function output
def test_request ( request) :
print( ' path info is' , request.path_info)
print ( ' method is', request.method)
print ( ' querystring is' , request.GET)
return HttpResponse( ' test request ok' )
Constructor format :
HttpResponse(content= Response body ,content_type= Response body data type , status= Status code )
effect :
Returns a response to the client browser , At the same time, carry the content of the response body
frequently-used Content-Type as follows
>
- 'text/html’( default ,html file )
- 'text/plain’( Pure text )
- 'text/css’(css file )
- 'text/javascript'(js file )
- 'multipart/form-data’( File submission )
- 'application/json'(json transmission )
- 'application/xml’(xml file )
GET,POST The most commonly used
http1.0
GET
HEAD ( test )
POST
HTTP1.1 newly added
PUT ( Update data )
DELETE ( Delete )
CONNECT ( agent )
OPTIONS ( negotiation )
TRACE ( Link test )
Here is a common HTTP Status code :
Five categories of status codes
1** The server receives the request , Requester is required to continue
2** success , Operation received and processed successfully
3** Redirect , Further action is required to complete the request
4** Client error , The request contains a syntax error or could not be completed
5** Server error , The server encountered an error while processing the request
The object of the dictionary , contain get All data in the request mode
POST: QueryDict Query dictionary objects , contain post All data in the request mode
FILES: A dictionary like object , Include all upload file information
COOKIES: Python Dictionaries , All inclusive cookie, Keys and values are strings
session: Dictionary like objects , Represents the current session
body: character string , Content of request body (POST or PUT)
scheme: Request protocol (‘http’ /‘https’)
request.get_full _path()∶ The full path of the request
request.META: Metadata in request ( The message header )
client IP Address -> request.META[‘REMOTE_ADDR’] :
# In the view function output
def test_request ( request) :
print( ’ path info is’ , request.path_info)
print ( ’ method is’, request.method)
print ( ’ querystring is’ , request.GET)
return HttpResponse( ’ test request ok’ )
## Django Respond to
Constructor format :
> HttpResponse(content= Response body ,content_type= Response body data type , status= Status code )
> effect :
> Returns a response to the client browser , At the same time, carry the content of the response body
```sh
frequently-used Content-Type as follows
>
- 'text/html’( default ,html file )
- 'text/plain’( Pure text )
- 'text/css’(css file )
- 'text/javascript'(js file )
- 'multipart/form-data’( File submission )
- 'application/json'(json transmission )
- 'application/xml’(xml file )
[ Outside the chain picture transfer in …(img-YnXkW921-1642079895356)]
GET,POST The most commonly used
[ Outside the chain picture transfer in …(img-NgqhpSNT-1642079895356)]
[ Outside the chain picture transfer in …(img-HFnux1UU-1642079895357)]
http1.0
GET
HEAD ( test )
POST
HTTP1.1 newly added
PUT ( Update data )
DELETE ( Delete )
CONNECT ( agent )
OPTIONS ( negotiation )
TRACE ( Link test )
[ Outside the chain picture transfer in …(img-UNX4USQh-1642079895357)]
[ Outside the chain picture transfer in …(img-VvJF5OBc-1642079895358)]
Here is a common HTTP Status code :
Five categories of status codes
1** The server receives the request , Requester is required to continue
2** success , Operation received and processed successfully
3** Redirect , Further action is required to complete the request
4** Client error , The request contains a syntax error or could not be completed
5** Server error , The server encountered an error while processing the request