Notes 4 of Python web development: foundation of Django development


Why Django

In a certain period of time, limited technology, the construction of a high-quality website, Django has become almost the only solution.
Django takes all the possibilities into consideration. To this extent, complexity means comprehensiveness. After all, time is more important!

Django features

  • Powerful database function

  • Powerful backstage function

  • Elegant website

  • Template system

  • Cache system

  • internationalization

Django application case

Abroad: Disqus, pinterest, instagram, NASA science, etc
Domestic: Douban, Zhihu, hungry, etc

Django development preparation

1. Install pip
2. Install Django
3. Install pyflakes
4. Atom installation plug-ins: atom Django, autocomplete python, platform ide terminal (pychar can also be used)

MTV Model

Web access process:

request ---->Django Web------>response

Internal structure of the process:



Models — data: as the agent of the database, operate the database through the model.
Templates: fill data into the web page for rendering.
Views — Views: return the rendered web page to the user, so that we can see the web page in the browser.
URLs — link: find the view corresponding to each URL.

Why should MTV be separated?

Complex functions, separate responsibilities can be handled, quickly find errors, easy to handle and maintain.

The simplest Django website:

Website creation process: P — > A — > d — > m — > V — > t — > u
P: Create project Django admin startproject firstsite
A: Create app Python startapp firstapp
D: Create database Python migrate
M: Create the database table models and create related model classes
5: Create views create related views def
T: Create templates / static and modify them with template language
U: Create the corresponding URL regular relationship and set the access URL

Analysis of specific steps

Create site:

django-admin startproject firstsite

The following files are generated:

    └── firstsite

Document explanation: : Django command running file, the general format is: Python Command name.
Wei init__ . py: is required for the directory structure of Python packages. : Django is used to configure files of global variables and attributes, such as the switch of debug and the location of static files. Associated to, corresponding to For a function (or generic class) in, visiting the website address corresponds to a function. : used when deploying the server Documents.

Internal structure of settings:

  • When debug = true, page errors will be directly thrown to the foreground, which is convenient for programmers to modify. In the real world, debug = false.

  • When debug = false, allow_ Hosts is required. If you don’t want to enter it, you can use allow_ Hosts = [‘*’] to allow all access.

  • INSTALLED_ Apps, users need to register under this column when they create a new app.

  • Templates: if you create a new Templates folder, you need to modify the dirs address:

      'DIRS': [os.path.join(BASE_DIR, 'templates').replace('\', '/')],
  • The default database is SQLite3, which is modified to MySQL as follows:

        DATABASES = {
            'default': {
                'ENGINE': 'django.db.backends.mysql',
                'NAME': 'testdb',
  • LANGUAGE_ Code =’en US’, Chinese is changed to ‘zh Hans’.

Create app

python startapp firstapp
(for the module of the project site, there can be multiple apps under a project)

The following files are generated:
Migrations: the PY script folder to generate the database.
Wei init__ : is required for the directory structure of Python packages. Background: you can have a powerful background with a small amount of code. : it is related to database operation. You can use this when saving or reading data. Of course, you can not use it when you can't use the database. : process the user's request from By rendering the web page in templates, you can output the displayed content, such as the user name after login and the data requested by the user. : test code for the web site.

Add app to install_ APPS

If the new app is not added to install_ In apps, Django cannot automatically find the template files (files under app name / templates /) and static files (files in app name / static /).

Create database

python makemigrations

The files generated by the makemigrations command will be saved to the migrations / directory to generate complex database creation statements.

python migrate

The previous makemigrations operation only generates the migration file and has not operated on the database. Next, execute the migrate command to complete the data consolidation and modification.

makemigrations vs migrate
Make migrations means to compile the model into SQL statements that MySQL can understand and store in the migrations folder.
Migrate is to execute the newly generated py file so that the database can modify the table according to the SQL statement. Because many punctuation marks in SQL statements conflict with Python, it is often necessary to escape the database to execute. Therefore, using the model module directly can save you a lot of trouble in writing SQL statements.

Start the server

python  Runserver temporary test server

case analysis

View is defined in views

t = Template(html_ String) ා used to transform HTML characters into templates, similar to punching.
C = context ({'person': person}) ා create a context context. Django requires that context must be in the form of a dictionary, similar to patching.
web_ Page = t.render (c) ා render the template and render the context into the template, similar to patching.
return HTTPResponse(web_ page)  # web_ The page string represented by page is converted into the specific visible web page response.

Extended reading:
1、Notes on illustrated http
2、Django foundation course (self improvement school)

This note comes from Netease micro professional “Python web development” section 1.1, 1.2
This paper is written byEverFightingThe creation is licensed by the knowledge sharing signature 3 Chinese Mainland License Agreement.