程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[Django] development: static file, application and model layer

編輯:Python

Static files

1. What is a static file

  • Files that cannot interact dynamically with the server are static files
  • Such as : picture ,css,js, Audio , video ,html file ( part )

2. Static file configuration

  • stay settings.py Configure the following two items in :

Configure the access path to the static file

  • Through which url Address to find static file
  • STATIC_URL = ‘/static/’
  • explain :

Specifies that static files need to be accessed through /static/xxx or 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

Example :

# file: setting.py
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)

3. Accessing static files

Use the access path of the static file to access

  • Access path : STATIC_URL = ‘/static/’
  • Example :
<img src="/static/images/lena.jpg">
<img src="http://127.0.0.1:8000/static/images/lena.jpg">

adopt {% static %} Tag access to static files

  • {% 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

  1. migrations Folder
    • Save intermediate files for data migration
  2. __init__.py
    • Application sub package initialization file
  3. admin.py
    • Background management profile of the application
  4. apps.py
    • Applied property profile
  5. models.py
    • Database related model mapping class files
  6. tests.py
    • Applied unit test file
  7. 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 :

  1. Create manually under application templates Folder
  2. 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 :

  1. Find the outer layer first templates Template under directory
  2. 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’

  • If the command has no output, you need to install

sudo apt-get install python3-dev default-libmysqlclient-dev

  • Make sure the above two libraries are installed , perform sudo pip3 install mysqlclient that will do

establish and Configuration database

Create database

  • establish create database Database name default charset utf8 ;
create database mywebdb default charset utf8 collate utf8_general_ci;

Configuration of database

  • sqlite Database configuration
# file: settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
  • mysql Database configuration
DATABASES = {
'default' : {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mywebdb', # Database name , You need to define
'USER': 'root',
'PASSWORD': '123456', # Administrator password
'HOST': '127.0.0.1',
'PORT': 3306,
}
}

About data SETTING Set up

ENGINE

  • Specify the backend engine for the database
'django.db.backends.mysql'
'django.db.backends.sqlite3'
'django.db.backends.oracle'
'django.db.backends.postgresql'
  • mysql The engine is as follows :

‘django.db.backends.mysql’

NAME

  • Specify the name of the database to connect to
  • 'NAME': 'mywebdb'

USER

  • Specify the user name to log in to the database
  • 'USER':'root'

PASSWORD

  • Connect the password of the database .
  • 'PASSWORD':'123456'

HOST

  • 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
    1. Establish correspondence between model classes and tables , It allows us to operate the database in an object-oriented way .
    2. According to the design of the model class to generate tables in the database .
    3. You can switch the database through simple configuration .
  • ORM benefits :
    1. 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 .
    2. 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
    1. For complex business , High use cost
    2. 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
  • Add one bookstore Of app
$ python3 manage.py startapp bookstore
  • register app
# file : setting.py
INSTALLED_APPS = [
...
'bookstore',
]
  • Add model class
# 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

  • Example :
money=models.DecimalField(
max_digits=7,
decimal_places=2,
default=0.0
)

6.FloatField()

  • Database type :double

Decimal values are used in programming languages and databases

7.EmailField()

  • Database type :varcha
  • Using strings in programming languages and databases

8.IntegerField()

  • Database type :int
  • Use integers in programming languages and databases

9.URLField()

  • Database type :varchar (200)
  • Using strings in programming languages and databases

10.ImageField()

  • Database type :varchar (100)
  • effect : In order to save the path of the picture in the database
  • Using strings in programming languages and databases

11.TextField()

  • Database type :longtext
  • effect : Represents character data of variable length
  • Reference documents https://docs.djangoproject.com/en/2.2/ref/models/fields/#field-types

Field options

  • 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)

For documentation, see :

https://docs.djangoproject.com/en/2.2/ref/models/fields/#field-options

Meta Inner class

  • 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 :
  1. choice 1 You will enter shell in , Manually enter a default value
  2. 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
  • Starting mode :
$ python3 manage.py shell

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved