Django from entry to proficiency: First [Django version. Python object-oriented. Web basics. Create Django project]

Article Directory

  • Beginner’s Guide to Django
    • 1 Introduction to Django
      • 1.1 History of Django
      • 1.2 Well-known sites that use Django
      • 1.4 Key features of Django
      • 1.5 How Django works
    • 2 Django Version Selection
      • 2.1 Python versions supported by Django
      • 2.2 Django version
    • 3 Django development Web program
      • 3.1 Python knowledge points
        • 3.1.1 Python Functions
        • 3.1.2 Python Object-Oriented
      • 3.2 Web Basics
      • 3.3 Install Django
      • 3.4 Create a Django project
        • 3.4.1 Creating a Django Project from the Command Line
        • 3.4.2 Creating a Django Project with PyCharm
    • 4 Common parameters and plug-ins of Django
      • 4.1 path () view function
      • 4.2 models. Py model parameter
      • 4.3. Template plug-in and technology
        • 4.3.1 Bootstrap
        • 4.3.2 jQuery
        • 4.3.2 AJAX
    • Brief summary

Beginner’s Guide to Django

Insert image description here

Welcome to the world of Django! Django is a very useful framework if you are interested in developing database-driven websites. In this blog post, we’ll cover the basics of Django, including its history, features, how to get started, and some of the well-known websites that use Django.


1 Introduction to Django

Django is an advanced Python Web framework for building Web applications.

Django provides a powerful set of tools and conventions to handle many of the chores of Web development, allowing developers to focus on writing the unique business logic of a Web site and quickly build a fully functional, easy-to-maintain Web site.

Django, under BSD copyright, was first released in July 2005, and the first official release, version 1.0, was released in September 2008.

Django uses MVT’s software design patterns, namely Model, View, and Template.

1.1 History of Django

Django was born in 2003 and was originally developed to meet the needs of news websites.
On July 21, 2005, Django was publicly released and made available under the BSD license.
Today, Django has evolved into a mature framework supported by a global community.

The history of the Django framework began in the fall of 2003, when web programmers Adrian Holovaty and Simon Willison, based at the Daily World newspaper in Lawrence, began building applications in Python. Jacob Kaplan-Moss was hired to join Django early in its development, shortly before the end of Simon Willison’s internship.

Django was originally developed to meet the needs of news websites with the goal of simplifying the creation of complex, database-driven websites. Django emphasizes reusability and “pluggability” of components, as well as the principles of small amounts of code, low coupling, rapid development, and not repeating yourself (DRY).

On July 21, 2005, Django was publicly released and made available under the BSD license. The frame is named in honor of guitarist Django Reinhardt, a Roma jazz guitar player whose music partially inspired Reinhardt.

By June 2008, it was announced that the newly formed Django Software Foundation (DSF) would maintain Django in the future. DSF is an independent organization established in the United States and is a 501 © (3) non-profit organization.

Today, Django has evolved into a mature framework supported by a global community, and its latest stable version is 5.0.6, released on May 7, 2024. Django continues to be the framework of choice for many developers and companies building modern Web applications.

1.2 Well-known sites that use Django

Foreign websites:

  • Instagram A popular social media platform that focuses on the sharing of images and videos.
  • Pinterest A platform that allows users to discover new ideas and inspiration.
  • Disqus A widely used blog comment hosting service.
  • Help page for Mozilla Firefox.
  • NASA: Some parts of the official NASA website were developed by Django.
  • The Washington Post: An influential news organization whose website uses Django to handle large volumes of views and traffic.

Domestic websites:

  • Douban A website that provides comprehensive information, user reviews and recommendation services for cultural commodities such as movies, books and music.
  • Zhihu A Chinese Q & a site where users can ask questions and share knowledge, experiences and insights.

The success of these sites demonstrates the reliability and efficiency of Django as a Web framework. Django’s design philosophy, security, and rapid development have made it the framework of choice for many developers and companies.

1.4 Key features of Django

  • Integrity: Provides “out of the box” functionality for almost anything a developer might want.

  • Versatility: Django can be (and has been) used to build almost any kind of website.

  • Django’s approach Security to security: Dedicated to helping developers avoid common security mistakes, Django provides a framework designed to automatically protect websites.

  • Rapid development Django is designed to help developers develop applications from concept to completion as quickly as possible.

  • Scalability: For the most heavily trafficked websites.

  • The DRY principle: Emphasize the reusability of components and follow the principle of not repeating yourself.

Django handles many of the drudgery of Web development, such as user authentication, database connectivity, CRUD (create, read, update, delete) operations, URL routing, form processing, and security, so developers can focus on writing the business logic that makes the site unique without having to reinvent the wheel.

Django follows the “battery included” philosophy and offers almost every feature Out of the box a developer could possibly want. Because everything you need is part of the framework, they work together seamlessly, follow consistent design principles, and have extensive and up-to-date official documentation.

1.5 How Django works

Django follows the MVT (Model-View-Template) architecture:

  • Model (model) Define the data structure of the program. That is, the data that the developer wants to present, usually from a database.
  • View (View): Process HTTP requests, get data from the model, pass to the template. It is a function or method that processes an HTTP request, imports the associated model, and determines what data to send to the template, and then returns the final result.
  • Template (Template): Defines how data is displayed. It is a file that describes how the results should be represented. Templates are typically HTML files that contain the layout of a Web page and the logic for how to display data.

Django is a very useful framework if you are interested in creating database-driven websites. Its ORM (Object-Relational Mapping) technology makes it easier to communicate with the database without writing complex SQL statements. Django also emphasizes component reusability, following the principle of DRY (don’t repeat yourself).


2 Django Version Selection

Determine which version of Django you want to use.

Django Is an open source version under the BSD license. The latest version of Python 3.x is recommended.

2.1 Python versions supported by Django

Because newer versions of Python are generally faster, have more features, and are better supported, the latest version of Python 3 is recommended.

You don’t lose anything by using older versions of Django, but you can’t take advantage of the improvements and optimizations of newer versions of Python.

Third-party applications used with Django are free to set their own version requirements.

Python version for Django version:

Django version Python Version
1.8 2.7、3.2(until the end of 2016)、3.3、3.4、3.5
1.9、1.10 2.7、3.4、3.5
1.11 2.7、3.4、3.5、3.6、3.7(added in 1.11.17)
2.0 3.4, 3.5, 3.6, 3.7
2.1 3.5, 3.6, 3.7
2.2 3.5、3.6、3.7、3.8 (added in 2.2.8)、3.9 (added in 2.2.17)
3.1 3.6、3.7、3.8、3.9(added in 3.1.3)
3.2 3.6、3.7、3.8、3.9、3.10(added in 3.2.9)
4.0 3.8、3.9、3.10
4.1 3.8、3.9、3.10、3.11(added in 4.1.3)
4.2 3.8、3.9、3.10、3.11、3.12(added in 4.2.8)
5.0 3.10、3.11、3.12
5.1 3.10、3.11、3.12
5.2 3.10、3.11、3.12、3.13

2.2 Django version

In general, if you are using the code in a production environment, you should use the stable version.

The Django project releases a full stable release about every eight months, with bug fix updates in between.

These stable releases contain APIs that are covered by our backward compatibility guarantee; if you’re coding against a stable release, you shouldn’t have any problems upgrading when the next official release is released.

Functional version (AB, A. B + 1, etc.) Is released approximately every eight months. These releases will include new features, improvements to existing features, and more.

Patch version (ABC, etc.) Will be released as needed to fix bugs and/or security issues. These versions will be 100% compatible with the relevant feature versions, unless they are not compatible for security reasons or to prevent data loss. Therefore, “Should I upgrade to the latest patch version?” The answer is always “yes”.

Some feature versions will be specified as Long Term Support (LTS) version. These releases will apply security and data loss fixes for a guaranteed period of time, typically three years.

Insert image description here

Release series Latest releases End of mainstream support Extended support ends
5.0 5.0.6 August 2024 2025 Year 4 moon
4.2 Long term support version 4.2.13 December 4, 2023 2026 Year 4 moon

Roadmap for future releases

Release series release date End of mainstream support Extended support ends
6.1 2026 Year 8 moon 2027 Year 4 moon December 2027
6.0 December 2025 2026 Year 8 moon 2027 Year 4 moon
5.2 Long term support version 2025 Year 4 moon December 2025 2028 Year 4 moon
5.1 2024 Year 8 moon 2025 Year 4 moon December 2025

3 Django development Web program

Before you start using Django, you need to know some basic Web knowledge and Python basics.

  • Python knowledge points: function, object-oriented.
  • Front-end development: Web basics, HTML, CSS, JavaScript.

3.1 Python knowledge points

Functions, Object Oriented

3.1.1 Python Functions

Code segments that Function are organized, reusable, and used to implement a single, or associated, function. Functions can improve the modularity of applications and the reuse of code. Python already provides many built-in functions, such as print(). But you can also create your own functions, which are called User-defined function.

To define a function of your own, the following is simple Rule:

  • A function code block begins with a def keyword, followed by a function identifier name and parentheses ().
  • Any incoming arguments and arguments must be placed between parentheses, which can be used to define arguments.
  • The first line of a function can optionally use a docstring — to hold the description of the function.
  • The function content starts with a colon: and is indented.
  • return [expression] Terminates a function, optionally returning a value to the caller, without an expression return None.

Insert image description here

Grammar

# Python Define function usage def Keywords,The general format is as follows:
def Function name(parameter list):
    function body
# by default,Parameter values ​​and parameter names are matched in the order defined in the function declaration。 

Function call Define a function: Give the function a name, specify the parameters contained in the function, and the structure of the code block.

Once the basic structure of this function is complete, you can execute it via another function call, or directly from the Python command prompt.

Parameter passing In python, types belong to objects, objects have different types, and variables have no types.

Parameter The following are the formal argument types that you can use when calling a function:

  • Required parameters Required parameters must be passed into the function in the correct order. The number at the time of invocation must be the same as at the time of declaration.
  • Keyword arguments Keyword arguments are closely related to function calls, which use keyword arguments to determine the values of the arguments passed in. Using keyword arguments allows the order of arguments to be different when a function is called than when it was declared, because the Python interpreter can match argument values with argument names.
  • Default parameters When a function is called, the default parameters are used if no parameters are passed.
  • Indefinite-length parameters You may need a function that handles more parameters than it was originally declared. These parameters are called variable-length parameters, and unlike the above two parameters, they are not named when they are declared. The basic syntax is as follows: “ `
    # Parameters marked with an asterisk * are imported as tuples to hold all unnamed variable parameters.
    def functionname([formal_args,] *var_args_tuple ):
    # function_docstring
    function_suitereturn [expression]

    # Parameters with two asterisks ** are imported as a dictionary.
    def functionname([formal_args,] **var_args_dict ):
    # function_docstring
    function_suitereturn [expression]

3.1.2 Python Object-Oriented

Python has been an object-oriented language since it was designed, and because of this, it is easy to create a class and an object in Python.

Some Basic characteristics Object-oriented of the:

  • Class: Used to describe a collection of objects with the same properties and methods. It defines the properties and methods that are common to each object in the collection. Objects are instances of classes.
  • Method: a function defined in a class.
  • Class variables: Class variables are common throughout the instantiated object. Class variables are defined in the class and outside the function body. Class variables are not normally used as instance variables.
  • Data members: Class variables or instance variables are used to manipulate data about a class and its instance objects.
  • Method override: If the method inherited from the parent class cannot meet the requirements of the child class, it can be overridden. This process is called method override, also known as method override.
  • Local variable: a variable defined in a method that acts only on the class of the current instance.
  • Instance variable: In the declaration of a class, a property is represented by a variable. Such a variable is called an instance variable. An instance variable is a variable decorated with self.
  • Inheritance: a derived class inherits the fields and methods of the base class. Inheritance also allows an object of a derived class to be treated as a base class object. For example, there is a design where an object of type Dog is derived from the Animal class, which mimics the “is an (is-a)” relationship (illustration, Dog is an Animal).
  • Instantiate: Create an instance of a class, a concrete object of a class.
  • Object: An instance of a data structure defined by a class. Object consists of two data members, a class variable and an instance variable, and a method.

Compared to other programming languages, Python adds the class mechanism with as little new syntax and semantics as possible.

Classes in Python provide all the basic features of object-oriented programming: the inheritance mechanism of classes allows multiple base classes, derived classes can override any method in the base class, and methods of the same name in the base class can be called in a method. An object can contain any amount and type of data.

Class definition The syntax format is as follows:

class ClassName:
    <statement-1>
    .
    .
    .
    <statement-N> 

After a class is instantiated, its properties are available; in fact, once a class is created, its properties are accessible through the class name.

Class object Class objects support two operations: property reference and instantiation.

Attribute references use the same standard syntax as all attribute references in Python: obj.name. When a class object is created, all names in the class namespace are valid attribute names.

Inside a Class class, use def the keyword to define a method. Unlike a normal function definition, a class method must contain parameters self, and it is the first parameter, self representing an instance of the class.

#!/usr/bin/python3

#class definition
class people:
    #Define basic properties
    name = ''
    age = 0
    #Define private properties,Private properties cannot be accessed directly outside the class
    __weight = 0
    #Define constructor
    def __init__(self,n,a,w):
        self.name = n
        self.age = a
        self.__weight = w
    def speak(self):
        print("%s explain: I %d age。" %(self.name,self.age))

# instantiate class
p = people('runoob',10,30)
p.speak() 

The output result of executing the above program is: runoob explain: I 10 age。

Inheritance Python also supports inheritance of classes, and if a language does not support inheritance, classes are meaningless. Derived classes are defined as follows:

class DerivedClassName(BaseClassName):
    <statement-1>
    .
    .
    .
    <statement-N> 

The subclass (derived class DerivedClassName) inherits the properties and methods of the parent class (base class BaseClassName).

BaseClassName (the base class name in the instance) must be defined in the same scope as the derived class. In addition to classes, you can also use expressions, which is useful when the base class is defined in another module:

Inherit more Python also has limited support for multiple forms of inheritance. The class definition of multiple inheritance is as follows:

class DerivedClassName(Base1, Base2, Base3):
    <statement-1>
    .
    .
    .
    <statement-N> 

Pay attention to the order of the parent classes in the parentheses. If there is the same method name in the parent class, but it is not specified when the subclass is used, python searches from left to right, that is, when the method is not found in the subclass, it searches from left to right whether the parent class contains the method.

Method override If the function of the method of your parent class does not meet your requirements, you can override the method of your parent class in the child class.

Private property __private_attrs of a Class properties and methods class: Starts with two underscores and declares the property as private and cannot be used or accessed directly outside the class. When self.__private_attrs used in a method inside a class.

Inside a Class class, use def the keyword to define a method. Unlike a normal function definition, a class method must contain parameters self, and it is the first parameter, self representing an instance of the class.

The name of self is not fixed and can be used this, but it is better to use it self according to the convention.

Private method of class __private_method : begins with two underscores, declaring the method as private and callable only inside the class, not outside it. self.__private_methods

Proprietary methods of the class:

  • __init__ : constructor, call __del__ when object is generated: destructor, use __repr__ when object is released: print, transform __setitem__ : assign __getitem__ by index: get value by index
  • __len__ : Get the length
  • __cmp__ : Comparison operation
  • __call__ : Function call
  • __add__ Addition operation
  • __sub__ Subtract operation
  • __mul__ : Multiplication
  • __truediv__ Division operation
  • __mod__ : Complementary operation
  • __pow__ : Power

3.2 Web Basics

The underlying web framework

  1. The network communication is shown in the following figure: 4 computers form a local area network and can communicate. Insert image description here Usually, a program written by a person needs to be deployed on a cloud server if he wants others to access it. Before deployment, he needs to rent a server (including public network IP) from the cloud platform. Common cloud servers include Alibaba Cloud, Huawei Cloud, Tencent Cloud and Amazon Cloud. A dual transceiver that allows the network to communicate with each other.

When we write it ourselves, we can communicate with each other on the network through the socket module.

  • My Computer \ [Server ]
import socket

# 1.Monitor the local machineIPand port
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('192.168.10.3', 8001))  # my own computerIP(passipComputers can be found, My program can be found through the port),port8001

# 2.How many people to wait for?
sock.listen(5)

while True:
    # 3.Application waiting for connection request,Someone to connect(block)
    conn, addr = sock.accept()

    # 4.Sent immediately after successful connection
    conn.sendall("welcomexxsystem".encode("utf-8"))

    # 5.Disconnect
    conn.close()

# 6.Stop the server program
sock.close()

# Bind to local machineipAnd procedures(port) Then let others connect Get it when connectedconandadd then send message 
  • Friend A’s computer (same LAN) \ [client ]
import socket

# 1. to specifyIPSend connection request
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('192.168.10.3', 8001))

# 2. Receive messages from you
message = client.recv(1024)  ##recvive  Accept sent message
print(message.decode("utf-8"))

# 3.Disconnect
client.close() 
  • Friend B’s Computer \ [Client ]
import socket

# 1. to specifyIPSend connection request
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('192.168.10.3', 8001))

# 2. Receive messages from you
message = client.recv(1024)
print(message.decode("utf-8"))

# 3.Disconnect
client.close() 
  1. Common software architecture
  • The BS architecture
Browser:Act as client
server:website 
  • CS framework, develop applications, such as QQ, Pycharm, NetEase Cloud Music (software installed on the computer)
client:Software installed on the computer。 NetEase Cloud Music
Server:NetEase server 

For programmers:

  • Web site, only need to write server-side procedures.
based ondjangoThe essence of development is the website(webapplication)
The browser on your computer is essentiallysocketImplement network communication。(The browser itself is already written) 
  • Software, client + server.
  1. Handwriting web framework (Handwriting simple web to build websites without using Django, flask, etc.)
import socket

# 1.Monitor the local machineIPand port
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('192.168.0.6', 9000))  # my own computerIP,port8001

# 2.How many people to wait for?
sock.listen(5)

while True:
    # 3.Application waiting for connection request,Someone to connect(block) -> Log in to your browser to connect with me
    conn, addr = sock.accept()

    # 4.Receive a message from the browser
    buf = conn.recv(2048)
    print(buf)

    # 5.Return data to the browser
    conn.send(b"HTTP/1.1 200 OK\r\n\r\n")
    conn.send(b"Hello, World")

    # 6.Disconnect
    conn.close()

# 6.Stop the server program
sock.close() 

Knowledge point: When the browser communicates with the website on the server side, there are several more rules.

  • Server: Website

  • Client: Browser

    • Create a connection
    • Send data, fixed format
    # First line of request header
    GET /xxx/xxx/?name=xxx&age=111 HTTP/1.1\r\n
    
    # Request header(Browser and other related information)
    Host: 192.168.0.6:9000\r\n
    Connection: keep-alive\r\n
    Upgrade-Insecure-Requests: 1\r\n
    User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36\r\n
    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\r\n
    Accept-Encoding: gzip, deflate\r\n
    Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7\r\n\r\n' 
    
    # First line of request header
    POST /xxx/xxx/ HTTP/1.1\r\n
    
    # Request header
    Host: 192.168.0.6:9000\r\n
    Connection: keep-alive\r\n
    Upgrade-Insecure-Requests: 1\r\n
    User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36\r\n
    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\r\n
    Accept-Encoding: gzip, deflate\r\n
    Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7\r\n\r\n(\r\n\r\nIndicates that the following is the request body)
    # Request body
    username=wupeiqi&password=123 
    
    When the browser essentially sends a request,Contains request headers and request body。
    - GETask
        - Only request header + No request body
        - Used between request headers \r\n
        - Used between request header and request body \r\n\r\n
    
    - POSTask
        - Only request header + There is a request body
        - Used between request headers \r\n
        - Used between request header and request body \r\n\r\n 
    
    • After one request and response, disconnect. The client sends the data and the server returns the data (login failure) and disconnects.
    • The HTTP protocol
    httpProtocol features:Stateless short connection。 
    httpApplications:The browser sends a request to the server,Just followhttpComes from agreement。
    - Request header+Request body ;Used between request header and request body \r\n\r\n ;Used between request headers \r\n
    - After one request and one response,Disconnect。  -> short connection。  ->How to embody statelessness?(friendBsend  to server The server knows they are friendsBGot it,Say welcome friendsB Then the connection is disconnected,then friendsBConnect again The server is still unknown as before. So it will be used latercookieto solve)
    - Remember later Request header+cookie
    (Specifically, friendsBSend to server The server knows they are friendsBGot it,And gave a voucher to send back to friendsB,make friendsBStore this certificate in the browser file,next time friendsBSending data to the server,I will take this certificate with me,When the server receives the certificate, it knows it is a friend.B)The server gives the client a token Next time the client comes with the token 
    

The only difference between a GET request and a POST is that a POST has a request body, which is used to transfer data. Of course, GET can also transfer data.

3.3 Install Django

Before installing Django, make sure your system requires a development environment with Python already installed. If you haven’t installed Python yet, download and install the required version of Python from the Python website.

Django installation is simple, using the package management tool pip to install Django:

# Install the latest versionDjango
pip install django
# Install the specified versionDjango4.1
pip install django==4.1 

The installed version can be viewed with the following command:

# python Version
python -V

# Django Version
python -m django --version 

3.4 Create a Django project

3.4.1 Creating a Django Project from the Command Line

** Create a new Django project mysite2 : **

django-admin startproject mysite2 

Directory structure of the project after creation:

.
|-- mysite2
|   |-- __init__.py     # an empty file,Tell Python This directory is a Python Bag
|   |-- asgi.py         # one ASGI compatible Web Server entrance,to run your project
|   |-- settings.py     # Should Django Project settings/Configuration
|   |-- urls.py         # Should Django The project URL statement; a copy of Django driven website"Table of contents"
|   `-- wsgi.py         # one WSGI compatible Web Server entrance,to run your project
`-- manage.py           # A practical command line tool,allows you to interact with the Django Projects interact 

Run the development server Start Django’s development server:

cd myproject
python manage.py runserver 

Create a Django application Create a new Django application:

python manage.py startapp app01 

The entire directory structure is now as follows:

.
|-- mysite2            # Project container
|   |-- __init__.py
|   |-- __init__.pyc            
|   |-- settings.py         
|   |-- settings.pyc            
|   |-- urls.py                 # url Configuration
|   |-- urls.pyc            
|   |-- views.py                # Added view files
|   |-- views.pyc           # Compiled view file
|   |-- wsgi.py         
|   `-- wsgi.pyc            
`-- manage.py 

Now that you understand the basic concepts of models, views, and templates, you can begin to practice building your project.

3.4.2 Creating a Django Project with PyCharm

PyCharm is recommended for creating Django projects

Create a Django project On the PyCharm homepage, click File-> newProject-> Django in the upper left corner.

Insert image description here Caution:

  • Command line, the project created is standard.
  • PyCharm adds something to the standard by default.
    • Create a templates directory [delete this templates folder and app01 create a templates new folder under the folder]
    • [Delete the content as shown in the figure] Insert image description here file description of the default project in the settings. Py:
mysite2
├── manage.py         【Project management,Startup project、createapp、Data management】【Do not move】【***often used***】
└── mysite
    ├── __init__.py
    ├── settings.py    【Project configuration】          【***Modify often***】
    ├── urls.py        【URLCorrespondence to functions】【***Modify often***】
    ├── asgi.py        【Receive network requests】【Do not move】
    └── wsgi.py        【Receive network requests】【Do not move】 

Create an app

python3.9 manage.py startapp app01 
- project
    - app,User Management   【Table Structure、function、HTMLtemplate、CSS】
    - app,Order management  【Table Structure、function、HTMLtemplate、CSS】
    - app,Backstage management  【Table Structure、function、HTMLtemplate、CSS】
    - app,website       【Table Structure、function、HTMLtemplate、CSS】
    - app,API       【Table Structure、function、HTMLtemplate、CSS】
    ..

Notice:Normally,Not much useapp,Created under this project1indivualappThat’s it。 

Insert image description here

The entire directory structure is now as follows:

├── app01
│   ├── __init__.py
│   ├── admin.py         【fixed,Don't move】djangoProvided by defaultadminBackstage management。
│   ├── apps.py          【fixed,Don't move】appStartup class
│   ├── migrations       【fixed,Don't move】Database change record
│   │   └── __init__.py
│   ├── models.py        【**important**】,Operation on database。
│   ├── tests.py         【fixed,Don't move】unit test
│   └── views.py         【**important**】,function。
├── manage.py
└── mysite2
    ├── __init__.py
    ├── asgi.py
    ├── settings.py
    ├── urls.py          【URL->function】
    └── wsgi.py 

Get started quickly

  • Make sure the app is registered []

  • Write URL and view function correspondence []

  • Write View Function [views. Py]

  • Start the Django project

    • Command-line launch “ `python manage. Py runserver ‘.
    • Pycharm starts Insert image description here

Now that you understand the basic concepts of models, views, and templates, you can begin to practice building your project.


4 Common parameters and plug-ins of Django

4.1 path () view function

Four parameters path() can be received, including two required parameters route, view and two optional parameters kwargs name.

# Syntax format:
path(route, view, kwargs=None, name=None)

# parameter
route: string,definition URL path part of。can contain variables,For example <int:my_variable>,to follow URL Capture parameters in and pass them to the view function。
view: view function,Handle requests matching the given route。Can be a function or a class-based view。
kwargs(Optional): a dictionary,Contains extra keyword arguments passed to view functions。
name(Optional): for URL The route is assigned a unique name,to reference it elsewhere in the code。This is useful for generating in templates URL Or it's very useful to do things like redirect in code。 

4.2 models. Py model parameter

Field type In Django’s models.py files, you can use a variety of fields to define the properties of the model and the fields of the table. The following are some common field types:

# Field
CharField:Used to store character data,designationmax_lengthParameter to set the maximum length。
IntegerField:Used to store integer data。
FloatField:Used to store floating point data。
BooleanField:Used to store boolean values。
DateField:Used to store dates。
DateTimeField:Used to store date and time。
TextField:Used to store long text data。
EmailField:Used to store email addresses。
URLField:for storageURLaddress。
ForeignKey:Used to establish foreign key associations。
ManyToManyField:Used to establish many-to-many relationships。
In addition to the above field types,There are many other field types to choose from,likeFileField、ImageField、UUIDFieldwait。Each field type has some specific parameters and options,Can be configured as needed。 

Properties in the type of the field In Django’s model, fields can use different properties to define their behavior and characteristics. The following are some common model field properties:

# Property parameters
null:Specifies whether the field is allowed to beNULLvalue。The default isFalse,That is, the field cannot be empty。
blank:Specifies whether the field can be blank。The default isFalse,That is, the field cannot be blank。
default:Default value for specified field。Can be a specific value or a callable object(Such as function)。
choices:A list of optional values ​​for the specified field。Can be a list containing tuples,Each tuple contains two values:Actual and displayed values ​​of options。
primary_key:Specifies whether the field is a primary key。by default,DjangoAn auto-incremented primary key field will be automatically added to each model.(id),But you can also designate other fields as primary keys。
unique:Specifies whether the value of the field must be unique。The default isFalse。
db_index:Specifies whether to create a database index for the field。The default isFalse。
editable:Specifies whether the field is editable。The default isTrue。If set toFalse,The field will not appear in the model form。
verbose_name:Specifies the human-readable name of the field。Used to display in the background management interface and forms。
help_text:Provide help text for the field,Used to display in the background management interface and forms。
auto_now:Specifies whether the field automatically updates to the current date and time each time the model is saved。
auto_now_add:The specified field is automatically set to the current date and time when the model object is first saved.,No more updates later。
related_name:Specify the name of the inverse relationship。Used to access related objects in related models。
on_delete:Specifies when the associated object is deleted,The behavior of this field。Common options includeCASCADE(Cascade delete associated objects)、PROTECT(Prevent deletion)、SET_NULL(Set asNULLvalue)wait。
These are just some common model field properties,DjangoMore properties and options are also provided,You can choose appropriate attributes to define the behavior of model fields according to actual needs.。 

For example, in Django models.CharField, in addition to max_length fields, there are other optional parameters that can be used to define CharField behaviors and properties. The following are models.CharField some of the fields commonly used in:

blank:Boolean value,Specifies whether the field can be empty。The default isFalse,That is, it cannot be empty。If set toTrue,is allowed to be empty。
null:Boolean value,Specifies whether the field can beNULL。The default isFalse,That is, it is not allowed to beNULL。If set toTrue,is allowed to beNULL。
default:Default value for specified field。Can be a specific value,It can also be a callable object(such as function or method)。The default value will be used when creating new objects,If no other value is provided。
choices:an optional picklist,Valid values ​​for restricting fields。Can be a list or a combination of tuples,Each element is a tuple containing two elements,The first element is the actual stored value,The second element is the label displayed to the user。For example:choices=[('M', 'Male'), ('F', 'Female')]。
verbose_name:The human-readable name of the field。if not provided,Djangowill automatically generate a。
help_text:Help text for the field,Used to provide a description of the field's purpose and input format。
validators:an optional list of validators,The value used to validate the field。Validators can be built-inDjangovalidator,It can also be a custom validator function。
unique:Boolean value,Specifies whether the value of the field must be unique。The default isFalse,i.e. allow duplicate values。If set toTrue,Then the value of the field is required to be unique。
error_messages:a dictionary,Error message for custom fields。Various error messages can be defined,likeblank(Error message when field is empty)、null(The fields areNULLerror message when)wait。 

These are models.CharField some of the fields commonly used in. Depending on your needs, you can use these fields to define and configure CharField the behavior and attributes of the.

Association between models In Django, models can be related by different types of relationships. The following are common model relationship types:

one-to-one relationship(One-to-One Relationship):There is only one relationship between one model instance and another model instance.。For example,A person can only have one ID number,One ID number can only correspond to one person。existDjangomiddle,can useOneToOneFieldto define a one-to-one relationship。

one-to-many relationship(One-to-Many Relationship):A model instance is related to multiple instances of another model。For example,An author can write multiple books,But a book can only have one author。existDjangomiddle,can useForeignKeyto define a one-to-many relationship。

many-to-many relationship(Many-to-Many Relationship):There is a many-to-many relationship between multiple model instances。For example,A student can take multiple courses,A course can also have multiple students。existDjangomiddle,can useManyToManyFieldto define a many-to-many relationship。

polymorphic relationship(Polymorphic Relationship):A model instance can be associated with multiple different model instances at the same time。For example,A comment can be associated with an article and a video at the same time。existDjangomiddle,Can use third-party libraries(likedjango-polymorphic)to implement polymorphic relationships。

self-referential relationship(Self-Referential Relationship):A model instance can be related to other instances of the same model。For example,An employee can have a superior leader,This superior leader is also an employee。existDjangomiddle,can useForeignKeyto define a self-referential relationship。 

These are common types of model relationships, and other types of relationships may be encountered in actual development. Django provides a rich set of relationship fields and management methods that make it easy to handle relationships between models.

Setting of class Meta in model In Django’s model, class Meta is an inner class that defines the metadata for the model. Metadata is additional information about a model that controls the behavior and characteristics of the model. class Meta You can include the following attributes:

# class Meta Property parameters

db_table:Specify the table name corresponding to the model in the database。

ordering:Specify the default sorting method for models。Can be a list containing field names,It can also be a string。

verbose_name:Specifies a human-readable name for the model。Used to display in the background management interface。

verbose_name_plural:Specifies the human-readable name of the plural form of the model。

unique_together:The field combination of the specified model must be unique。Can be a tuple or list containing field names。

indexes:Specify the database index of the model。Can be a containingmodels.Indexlist of objects。

constraints:Specify database constraints for the model。Can be a containingmodels.CheckConstraint、models.UniqueConstraintormodels.ForeignKeyConstraintlist of objects。

default_related_name:Specifies the default name of the model's inverse relationship。Used to access related objects in related models。

abstract:Specifies whether the model is an abstract model。Abstract models cannot be instantiated directly,Can only be inherited by other models。

app_label:Specifies the name of the application to which the model belongs。

db_tablespace:Specify the tablespace of the model in the database。

managed:Specify whether theDjangoAutomatically manage database tables for models。The default isTrue,Expressed byDjangoAutomatically create and maintain table structures。 

By defining a class Meta, you can have more granular control and configuration of the model. These metadata attributes can affect the database table structure of the model, the display of the background management interface, and the sorting of query results.

Def str (self) setting in model In Django’s model, def __str__(self) is a special method for defining a string representation of a model object. This method is called when the model object is printed, displayed in a back office interface, or other context, and returns a readable string representation.

Typically, def __str__(self) a method returns the value of a field of a model object to better represent the object. For example, if your model has a field named name, you can return the value of the field in a def __str__(self) method as follows:

class MyModel(models.Model):
    name = models.CharField(max_length=100)
    # other fields...

    def __str__(self):
        return self.name 

In this example, def __str__(self) the method returns the value of the name field of the model object. When the model object is printed or displayed, the value is represented as a string.

By defining a def __str__(self) method, you can customize the string representation of the model object to better represent and identify the model object. This is useful for readability during debugging and development.

4.3. Template plug-in and technology

4.3.1 Bootstrap

Bootstrap From Twitter, the most popular front-end framework out there.

Bootstrap is based on HTML, CSS, JAVASCRIPT, it is simple and flexible, making Web development faster. Bootstrap was developed by Mark Otto and Jacob Thornton of Twitter. Bootstrap is an open source product released on GitHub in August 2011. Make sure you have a basic knowledge of HTML, CSS, and JavaScript before you get started.

Bootstrap features:

  • Mobile device first: As of Bootstrap 3, the framework includes mobile-first styles throughout the library.

  • Browser support: Bootstrap is supported by all major browsers.

  • Easy to get started: As long as you have a basic knowledge of HTML and CSS, you can start learning Bootstrap.

  • Responsive Design: Bootstrap’s responsive CSS adapts to desktops, tablets, and phones. Insert image description here

  • Provides a simple and unified solution for back-end developers to create interfaces.

  • Includes powerful built-in components for easy customization.

  • Web-based customization is also available.

  • Bootstrap is open source.

Contents of the Bootstrap package:

  • Basic structure: Bootstrap provides a basic structure with a grid system, link styles, and backgrounds.
  • CSS: Bootstrap comes with the following features: global CSS settings, defining basic HTML element styles, extensible classes, and an advanced grid system.
  • Components: Bootstrap includes a dozen reusable components for creating images, drop-down menus, navigation, alert boxes, pop-up boxes, and more.
  • JavaScript Plugins: Bootstrap includes a dozen custom jQuery plugins. You can include all of the plug-ins directly or individually.
  • Customization: You can customize the Bootstrap components, LESS variables, and jQuery plugins to get your own version.
4.3.2 jQuery

jQuery Is a JavaScript library.

JQuery greatly simplifies JavaScript programming. The jQuery library can be added to a Web page with a single line of markup. JQuery is a lightweight “write less, do more” JavaScript library. The jQuery library contains the following features:

  • HTML element selection
  • HTML element operation
  • CSS operation
  • HTML event functions
  • JavaScript effects and animation
  • HTML DOM traversal and modification
  • AJAX
  • Utilities
4.3.2 AJAX

AJAX is a technology that enables you to update parts of a Web page without having to reload the entire page.

AJAX = Asynchronous JavaScript and XML. AJAX is not a new programming language, but a new way to use existing standards. The best thing about AJAX is that you can exchange data with the server and update parts of the Web page without reloading the entire page. AJAX does not require any browser plug-ins, but it does require the user to allow JavaScript to execute on the browser. XML Http Request is just one way to implement Ajax. AJAX = Asynchronous JavaScript and XML.

AJAX is a technology for creating fast, dynamic Web pages. AJAX allows web pages to be updated asynchronously by exchanging a small amount of data with the server in the background. This means that you can update a portion of a Web page without reloading the entire page. Traditional Web pages (not using AJAX) must reload the entire Web page if they need to update content. There are many examples of applications using AJAX: Sina Weibo, Google Maps, Kaixin, and so on.

AJAX application: AJAX is based on existing Internet standards and uses them in conjunction.

  • XML Http Request objects (asynchronously exchanging data with the server). Use XHTML + CSS to express information.
  • JavaScript/DOM (information display/interaction). Use JavaScript to manipulate the DOM (Document Object Model) to perform dynamic effects.
  • CSS (to style data).
  • XML (as a format for transforming data). Use XML and XSLT to manipulate data, and use XMLHttpRequest or the new Fetch API for asynchronous data exchange with web servers.

Note that AJAX is distinct from RIA technologies such as Flash, Silverlight, and Java Applets, and that AJAX applications are browser and platform independent!