{% static %} Indicates the static file access path
load static
{% load static %}
When using static resources
grammar :
{% static ' Static resource path ' %}
Example :
<img src="{% static 'images/lena.jpg' %}">
Django Application in - app
Apply to Django The project is an independent business module , You can include your own route , View , Templates , Model
Create an app
Creating steps
use manage.py The subcommand in startapp Create application folder :python3 manage.py startapp apply name
Such as :python3 manage.py startapp music
stay settings.py Register an application in
INSTALLED_APPS = [
# ....
'user', # User information module
'music', # Music module
]
The structure of the application
migrations Folder
Save intermediate files for data migration
__init__.py
Application sub package initialization file
admin.py
Background management profile of the application
apps.py
Applied property profile
models.py
Database related model mapping class files
tests.py
Applied unit test file
views.py
The file that defines the view processing function
Distributed routing for applications
Django in , Main route profile (urls.py) You don't have to deal with user specific routing , The main route configuration file can be used to distribute requests ( Distributed request processing ). Specific requests can be handled by their respective applications
Pictured :
include function
effect :
It is used to distribute the routing profile that transfers the current route to each application urlpatterns Distributed processing
Function format
include(‘app Life word .url Module name ’)
modular app Life word /url Module name .py There must be... In the file urlpatterns list It needs to be used before use from django.conf.urls import include Import this function
Applied templates
The template directory can be configured inside the application :
Create manually under application templates Folder
settings.py Middle confirmation TEMPLATE In the configuration item Of ‘APP_DIRS’ value for example : ‘APP_DIRS’: True
Under application templates and Outer layer templates When they all exist ,django You have to find template rules :
Find the outer layer first templates Template under directory
Press INSTALLED_APPS The configuration of the Application order Layer by layer search
The model layer
Django Configuration and use under mysql database
Model (Models)
install mysqlclient [ edition mysqlclient 1.3.13 above , The official website is currently 1.4.x]
Confirm before installation ubuntu Installed or not python3-dev and default-libmysqlclient-dev
sudo apt list --installed|grep -E ‘libmysqlclient-dev|python3-dev’
Which host to use when connecting to the database .
'HOST':'127.0.0.1'
PORT
The port used to connect to the database .
'PORT':'3306'
Model (Models)
The model is a model Python class , It is from django.db.models.Model Derived subclasses .
A model class represents a data table in the database
Each class attribute in the model class represents a field in the database .
Model is the interface of data interaction , It is the method and way to represent and operate the database
Django Of ORM frame
ORM(Object Relational Mapping) Object relation mapping , It's a programming technology , It allows you to operate on the database using classes and objects , So as to avoid passing through SQL Statement operation database
ORM The role of the framework
Establish correspondence between model classes and tables , It allows us to operate the database in an object-oriented way .
According to the design of the model class to generate tables in the database .
You can switch the database through simple configuration .
ORM benefits :
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 .
You can easily change the database through simple configuration , Without changing the code .
ORM shortcoming
For complex business , High use cost
Convert to SQL sentence , Convert to object according to the result of query , Performance loss during mapping .
ORM schematic
Model example
This example adds a bookstore_book Data sheet to store bibliographic information in the library
# file : bookstore/models.py
from django.db import models
class Book(models.Model):
title = models.CharField(" Title ", max_length=50, default='')
price = models.DecimalField(' pricing ', max_digits=7, decimal_places=2, default=0.0)
Database migration
Migration is Django Synchronize your changes to the model ( Add fields , Delete model, etc ) The way to your database schema
1. Generate or update migration files
Apply the models.py File generates an intermediate file , And keep it in migrations In the folder
python3 manage.py makemigrations
2. Execute the migration script
Execute the migration program to realize the migration . Apply the migrations The intermediate files in the directory are synchronized back to the database
python3 manage.py migrate
notes : The above two steps of migration are required before running the service program after modifying the model class .
Model class Models establish
The model class needs to inherit from django.db.models.Model
Models Grammatical norms of
from django.db import models
class Model class name (models.Model):
Field name = models. Field type ( Field options )
The model class name is part of the data table name , It is suggested that class names should be capitalized
The field name is the class attribute name of the current class , This name will be used as the field name of the data table
Field types are used to map to the types of fields in the data table
Field options provide additional parameter information for these fields
Field type
1.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
2.CharField()
Database type :varcha
Be careful :
Must specify max_length Parameter values
3.DateField()
Database type :date
effect : Indicates the date
Parameters :
auto_now: Every time you save an object , Automatically sets this field to the current time ( Value :True/False).
auto_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
4.DateTimeField()
Database type :datetime (6)
effect : Represents the date and time
The parameters are the same as DateField
5.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
Field options , Specify additional information for the created column
Multiple field options are allowed , Use between multiple options , separate
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
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 .
Example :
# 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, null=False, db_index=True)
Use the inside Meta class To give attributes to the model ,Meta There are many built-in class properties under class , You can do some control over the model class
Example :
# file : bookstore/models.py
from django.db import models
class Book(models.Model):
title = models.CharField(" Title ", max_length=50, default='')
price = models.DecimalField(' pricing ', max_digits=7, decimal_places=2, default=0.0)
class Meta:
db_table = 'book' # You can change the table name corresponding to the current model class
Error handling method of database migration
When executed $ python3 manage.py makemigrations How to handle the following migration errors
error message
You are trying to add a non-nullable field 'des' to book without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit, and let me add a default in models.py
Select an option:
Translated into Chinese as follows :
You tried to add a non empty field 'des' There is no default ; We can't do this ( The database needs to populate existing rows )
Please select repair :
1) Now provide a one-time default ( A null value for this column will be set for all existing rows )
2) sign out , Let me in models.py Add a default value to
Select an option :
The reason for the error
This error occurs when a new field is added to the model class
The principle is After adding a new field , The database does not know how the original existing data should be assigned to the new field , So when adding a field , Be sure to add default The default value is .
processing method :
choice 1 You will enter shell in , Manually enter a default value
Exit the current process of generating migration files , Modify it yourself models.py, Add a new default=XXX Default value ( Recommended )
The solution to the confusion of database migration files
Delete all migrations All in 000?_XXXX.py (__init__.py With the exception of )
Delete database
sql> drop database mywebdb;
Recreate database
sql> create datebase mywebdb default charset…;
To regenerate the migrations All in 000?_XXXX.py
python3 manage.py makemigrations
Re update the database
python3 manage.py migrate
Basic operation of model layer
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)
Manager 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
class MyModel(models.Model):
...
MyModel.objects.create(...) # objects Is the manager object
Create data objects
Django Use an intuitive way to express the data in the database table as Python object
Creating every record in the data is creating a data object
MyModel.objects.create ( attribute 1 = value 1, attribute 2 = value 1,…)
success : Returns the created entity object
Failure : Throw an exception
establish MyModel Instance object , And call save () Preservation
obj = MyModel( attribute = value , attribute = value )
obj. attribute = value
obj.save()
Django shell Use
stay Django Provides an interactive operation project called 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
stay Django Shell Only simple operations can be performed under , Cannot run remote mode