Notes 4 of Python web development: foundation of Django development

Time:2020-10-26

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:

request——————>urls——————>views<——————models
                              |
                              |
                              ↓
                          templates

MTV

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 manage.py startapp firstapp
D: Create database Python manage.py 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
    ├── manage.py
    └── firstsite
        ├── __init__.py
        ├── settings.py
        ├── urls.py
        └── wsgi.py

Document explanation:
manage.py : Django command running file, the general format is: Python manage.py Command name.
Wei init__ . py: is required for the directory structure of Python packages.
setting.py : Django is used to configure files of global variables and attributes, such as the switch of debug and the location of static files.
urls.py Associated to, corresponding to views.py For a function (or generic class) in, visiting the website address corresponds to a function.
wsgi.py : used when deploying the server wsgi.py 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',
                'USER':'younger',
                'PASSWORD':'123',
                'HOST':'',
                'PORT':'',
            }
        }
    
  • LANGUAGE_ Code =’en US’, Chinese is changed to ‘zh Hans’.

Create app

python manage.py 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.
admin.py Background: you can have a powerful background with a small amount of code.
models.py : 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.
views.py : process the user's request from urls.py 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.
tests.py : 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 mange.py makemigrations

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

python mange.py 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  mange.py  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)

remarks
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.

Recommended Today

Stack chain storage

Linked list implementation stack Create three files: stacklinked. H, stacklinked. C, stacklinkedtest. C stackLinked.h #ifndef STACK_LINKED_H_ #define STACK_LINKED_H_ #ifdef __GNUC__ #define DEPRECATED __attribute__( (deprecated) ) #elif defined(_MSC_VER) #define DEPRECATED __declspec( deprecated ) #else #define DEPRECATED #endif #ifndef PTOI #define PTOI( p ) ((int32_t)(int64_t)(p)) #endif #ifndef ITOP #define ITOP( i ) ((void *)(int64_t)(i)) #endif #define ADT […]