.

Static files

  • Static file configuration -settings.py
    • Configure the static file access path.
      • Look for static files at that URL
      • STATIC_URL = ‘/static/’
      • Description:
        • When accessing static specified file is need through/static/XXX or http://127.0.0.1:8888/static/xxx [XXX on behalf of the exact location of the static resources]
  • Configure the storage path for static files. STATICFILES_DIRS STATICFILES_DIRS stores the storage path for static files on the server
# file: setting.py STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static')) # file: setting.py STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'))Copy the code
  • For example, access the static file -img tag in the template
    • Scheme 2
1. Load static - {% load static %} 2. Use static resource -{% static 'static resource path '%} 3. Example <img SRC ='{% static 'imgage/xxx.jpg'%}'>Copy the code
  • A small case
    • Start by creating a new project
Django_03 # create a new project django-admin startProject mysite3Copy the code
  • Run mysite3
python3 manage.py runserver 8888
Copy the code

  • Modify the configuration
Settings. py # 1 inside # mysite3. Let's comment out CSRF, because now when we send a post request that triggers CSRF security, Will quote 403 MIDDLEWARE = [' django. MIDDLEWARE. Security. SecurityMiddleware ', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] # 2. Configure DIRS' DIRS': [os.path.join(BASE_DIR, 'templates')], # 3. LANGUAGE_CODE = 'zh-hans' TIME_ZONE = 'Asia/Shanghai' # 4. Configure STATICFILES_DIRS STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)Copy the code
  • Creating a folder

  • Create a view
# views.py
from django.shortcuts import render


def test_static(request):
    return render(request, 'test_static.html')
Copy the code
  • Create a template
# test_static.html <! DOCTYPE HTML > < HTML lang="en"> <head> <meta charset="UTF-8"> <title> Test static file </title> </head> <body> <! - an absolute address - > < img SRC = "http://127.0.0.1:8888/static/image/django-01.jpg" Alt = "" width =" 300 px "height =" 200 px "> <! <img SRC ="/static/image/django-01.jpg" Alt ="" width="300px" height="200px"> <! {% static %} <img SRC ="{% static 'image/django-01.jpg' %}" Alt ="" width="300px" height="200px"> </body> </html>Copy the code
  • Configure the routing
# urls.py
path('test_static', veiws.test_static)
Copy the code

Django applications and distributed routing

application

  • Application in a Django project is a separate business module that can contain its own routes, views, templates, and models

Create an

  • Step 1
    • Create an application folder with the startapp subcommand in manage.py
python3 manage.py startapp xxxx
Copy the code
  • Step 2
    • Configure to install this app in the INSTALLED_APPS list of settings.py
INSTALLED_APPS = [#... 'user', # user info module 'music' # music module]Copy the code

Distributed routing

  • In Djangoa, the main routing profile (urls.py) does not handle user-specific routes. The main routing profile can distribute requests (distributed request processing). Specific requests can be handled by the respective application

  • Configuring distributed Routing
    • Call the include function in step 1- main routing
    • Syntax: include(‘app name.url module name ‘)
    • Role: Distributed processing of urlpatterns used to forward current routes to the routing profiles of individual applications
    • In http://127.0.0.1:8888/music/index, for example

  • Step 2- Configure urls.py in the app. Manually create urls.py in the app. The content structure is exactly the same as that of the main route

  • run

Exercise – Configuring distributed routing

  • Create two applications
    • Create the Sport application and register
python3 manage.py startapp sport
Copy the code
  • Create a News application and register it
python3 manage.py startapp news
Copy the code

  • Create a distributed routing system
    • Configure the main route
   path('news/', include('news.urls')),
    path('sport/', include('sport.urls')),
Copy the code

  • http://127.0.0.1:8888/sport/index to sport application index_view () function
# Create urls.py from django.urls import path from. Import views urlpatterns = [path('index', views.index_view)]Copy the code
  • http://127.0.0.1:8888/news/index to news application index_view () function
# create urls.py from django.urls import path from. Import views urlpatterns = [path('index', views.index_view)]Copy the code

Application template

  • You can configure a template directory within an application
  1. Create the templates folder manually
  2. Settings. Py enables the template mapping function

The value of ‘APP_DIRS’ in the TEMOLATE configuration item is true

  1. When templates and templates are both present, Django has to look for template rules

3.1 Preferentially Search for templates in the outer Templates directory

3.2 Application Search In INSTLLED_APP Configuration Layer by layer

  • Take the News app for example

1. Create the Templates folder

2. Create a view in views.py in the news file

Def index_view(request): # return HttpResponse(request, 'news/index.html')Copy the code
  1. Solve the problem that the application sequence of the file with the same name in the outer Tempaltes folder is searched layer by layer in NSTLLED_APP configuration

Model layer and ORM introduction

Template layer – Definitions

  • Model layer – responsible for communicating with data

Django configuration mysql

  • Creating a database
  • Run the mysql database
    • Create Database Database name default Charset UTf8
    • Usually the database name is the same as the project name
  • Settings. py for database configuration
    • Modified the content of DATABASES from SQlite3 to mysql

Mysql database = {'default': {'ENGINE': 'django.db.backends.mysql', 'NAME': 'mysite3', 'USER': 'root' and 'PASSWORD' : 'aa123456', 'HOST' : '127.0.0.1', 'PORT', '3306'}}Copy the code
  • ENGINE- Specifies the database storage ENGINE
'django.db.backends.mysql'
'django.db.backends.sqlite3'
'django.db.backends.oracle'
'django.db.backends.postgresql'
Copy the code
  • NAME- Specifies the NAME of the database to connect to
  • USER – Specifies the USER name to log in to the database
  • PASSWORD – Indicates the PASSWORD of the database
  • HOST/PORT – IP address and PORT for connecting to a specific database

What is a model

  • A Model is a Python class that is a subclass of Django.db.models.Model
  • A model class represents a table in a database
  • Each class attribute in the model class represents a field in the database
  • A model is an interface for data interaction and a way of representing and manipulating a database

ORM framework

  • define
    • Object Relational Mapping (ORM) is a program technique that allows you to use class and object databases to operate without using SQL statements to manipulate databases
  • Function:
    • Mapping between model classes and tables allows us to manipulate the database in an object-oriented manner
    • Generate tables in the database from the designed model classes
    • Database switching can be performed with simple configuration
  • advantages
    • You only need object-oriented programming, you don’t need to write database oriented code
      • Operations on the database are translated into operations on class properties and methods
      • No need to write SQL statements for various databases
    • The decoupling of data model and database is realized, and the differences in operation of different databases are shielded
      • Not the same concern is mysql. oracle…. The internal details of the database
      • Databases can be easily replaced with a simple configuration and no code changes are required
  • disadvantages
    • For complex services, the usage cost is high
    • Converting objects into SQL statements based on their operations and converting objects into objects based on the query results results in performance loss during the mapping process
  • map

  • Model example
    • This example adds a Bookstore app to add a Bookstore_book data table to store library bibliographic information
      • Add a Bookstore app
    • Add model classes and register your APP
  • Database Migration
    • Migration is how Django synchronizes changes you make to a model (adding fields, deleting models, etc.) to your database schema
      • Generate migration files – Run python3 Manage. py makemigbar to generate an intermediate file from the models. Py file and save it in the Migrations folder

  • Run the migration script – Run Python3 manage.py Migrate to perform the migration and synchronize the intermediate files in the migrations directory under each application back to the database

  • Model class – Create
From django.db import Models class (models.Model) : = models. Field type (field options)Copy the code
  • Hoisting & Migrate

04-ORM- Base field and option 1

Create model class process

  • Any changes to the structure must be made on the corresponding model class
  • Example: Add a field varchar(100) named info to the bookstore_book table
    • The solution
      • Add corresponding class attributes to the model class
      • Perform database migration
Add field info = models.CharField(' description ', max_length=100, default='') # 2. Database migration (running on terminals) PYTHon3 Manage. py MakemigRations PYTHon3 manage.py MigratCopy the code
  • Viewing a Database

The field type

  • BooleanField ()

    • Database type: tinyint (1)
    • In programming languages: use true or False to represent values
    • In the database: use 1 or 0 to represent a specific value
  • CharField ()

    • Database type: VARCHAR
    • Note: the max_length parameter must be specified
  • DateField ()

    • Database type: Date

    • Function: Indicates the date

    • Parameters:

      • 1. Auto_now: Automatically sets this field to the current time each time an object is saved (value: True or False).
      • 2. Auto_now_add: Automatically sets the current time when the object is created for the first time (value: True/False)
      • Default: Set the current time (value: time in a string format, for example, ‘2019-6-1’).
  • DateTimeField()

    • Database type: datetime (6)
    • Function: Indicates the date and time
    • Parameters with a DateField
  • FloatFieid ()

    • Database type: double
    • Decimals are used to represent values in programming languages and databases
  • DecimalField()

    • Database type: Decimal (x, Y)

    • In programming languages: use decimals to represent the value of the column

    • In the database: Use decimals

    • Parameters:

      • Max_digits: Total number of digits, including digits after the decimal point. The value must be greater than or equal to Decimal_placse
      • Decimal_places: Number of digits after the decimal point
  • EmailField ()

    • Database type: VARCHAR
    • Strings are used in programming languages and databases
  • IntegerField ()

    • Database type: int
    • Integers are used in programming languages and databases
  • ImageField ()

    • Database type: VARCHAR (100)
    • Action: A path to save an image in a database
    • Strings are used in programming languages and databases
  • TextField ()

    • Database type: longtext
    • Function: Represents indefinite character data

Create a model class

  • Add a model class to the Bookstore /models.py application

  • The Author – the Author

    • Name-charfield The name contains a maximum of 11 characters
    • Age-intergerfield age
    • EmailField Specifies the email address
# bookstore/models.py class Author(models.Model): Name = models.charfield (' name ', max_length=11) age = models.integerfield (' age ') Email = models.emailfield (' email ')Copy the code
Python3 Manage. py Makemigbar python3 manage.py MigrateCopy the code

Go to mysql to see if there is an extra table

05-ORM- Base fields and option 2

Model classes – Field options

  • Field option that specifies additional information about the column to be created

  • Allow multiple field options to appear, multiple options used between, separated

  • primary_key

    • If set to True, the column is the primary key. If a field is specified as the primary key, the ID field is not created in this database table
  • blank

    • When set to true, the field can be empty, and when set to False, the field is mandatory
  • null

    • If set to True, the column value is allowed to be null
    • The default value is False. If this is False, it is recommended to add the default option to set the default value
  • default

    • Set the default value for the column. This is recommended if the field option is null= False
  • db_index

    • If set to true, indexes are added to the column
  • unique

    • If set to True, the value of this field must be unique in the database (it cannot be repeated)
  • db_column

    • Specifies the name of the column, using the attribute name if not specified
  • verbose_name

    • Set the display name of this field on the Admin page

Field options examples

Name = models.CharField(max_length=30, unique=true, null =False, db_index= true)Copy the code

Model class -Meta class

  • Meta class – Definition

    • Use the inner Meta class to assign attributes to the model. The Meta class has many inner key class attributes to give the model some control
    • The sample
# bookstore/ models.py class Book(models.Model): Title = models.charfield (' title ', max_length=50, default='') price = models.decimalField (' price ', max_digits=7, Decimal_places =2, default=0.0) info = models.CharField(' description ', max_length=100, default='') Class Meta: db_table =' book'Copy the code
  • The migration

  • Viewing a Database

Practice modifying model classes

  • 1. Change the model class -book to BOOK

    • Title -CharField (50) – Title (only)
    • Pud-charfield (100) – Press (Not empty)
    • Price -DecimalField – Total book price 7/ 2 decimal places
    • Market_price – Total retail price of books 7/ 2 decimal places
    1. Model class -Author (table name Author)

      • Name – CharField (11) – Name (not empty)
      • Age-integerfield – Age The default value is 1
      • Email-emailfiel – The email address can be empty
  • demo

# models.py class Book(models.Model): Pud = models.CharField(' max_length ', 'max_length ',' default ', 'True') Default = ") price = models.DecimalField(' price ', max_digits=7, decimal_places=2, Default =0.0) market_price = models.DecimalField(' retail ', max_digits=7, decimal_places=2, default=0.0) class Meta: db_table = 'book' class Author(models.Model): Name = models.CharField(' name ', max_length=11) age = models.IntegerField(' age ', default=1) Email = models.emailfield (' email ', null=True) class Meta: db_table = 'author'Copy the code
  • The migration

  • Look at the mysql

ORM- Basic Operations – Create data

The ORM – operation

  • Basic operations include add, delete, change, and query operations, namely (CRUD operations)
  • CRUD refers to add (Create), Read (query), Update (Delete), and Delete (Delete) when doing computation.
  • ORM CRUD Core — model class. Manager object

Create the data

  • Django ORM uses an intuitive way to represent data in database tables as Pyhton objects

  • Creating each record in the data creates a data object

  • Plan a

    • Mymodel.objects.cteate (Attribute 1= value 1, Attribute 2 = value 1..)

      • Success: Returns the created entity object
      • Failure: Throws an exception
  • Scheme 2

    • Create the MyModel instance object and save it by calling save ()
Obj = MyModel(Property = value, property = value) obj. Property = value obj.save()Copy the code

Django Shell

  • Django provides an interactive action project called the Django Shell that can perform actions in response to project code in interactive mode

  • Instead of writing view code, the Django Shell lets you do this directly

  • Note: Re-enter the Django shell when the project code changes

  • Startup mode:

    • Python3 manage.py shell
  • practice

    • Add the following data to the book table using the Django shell
    • Book information

Once created, check mysql