Day 58: getting started with Web development Django

by Aurora

Today, I'd like to introduce Django, another web development framework of Python. It is an open-source Web application framework customized based on python. It originated from an online news web site at first, and then opened up in 2005. Django has large and comprehensive functions. It provides a one-stop solution, which allows developers to spend a lot of time on selecting application infrastructure before development. It has many powerful third-party plug-ins, which can make us develop a website more quickly and conveniently.

Django framework

Django adopts the Web framework constructed by MVC (i.e. Model M, view V and controller C), but since the part of the controller that accepts user input is handled by the framework itself, it pays more attention to Model, template and Views in the development of Django, which is called MTV mode.
The main purpose of Django is to develop database driven websites easily and quickly. It emphasizes code reuse. Multiple components can easily serve the whole framework in the form of "plug-ins". Django has many powerful third-party "plug-ins". You can even easily develop your own toolkit, which makes Django highly extensible. It also emphasizes the principles of rapid development and DRY(Do Not Repeat Yourself).

Install Django Library

Like other modules, Django installation is very simple. Next, install it through pip3 package manager

pip3 install django

After installing Django, you can use Django admin, an administrative tool, to create projects, create applications, start services and other operation commands.

$ django-admin
cleanup           -- remove old data from the database
compilemessages   -- compile .po files to .mo for use with gettext
createcachetable  -- creates table for SQL cache backend
createsuperuser   -- create a superuser
dbshell           -- run command-line client for the current database
diffsettings      -- display differences between the current settings and Django defaults
dumpdata          -- output contents of database as a fixture
flush             -- execute 'sqlflush' on the current database
inspectdb         -- output Django model module for tables in database
loaddata          -- install the named fixture(s) in the database
makemessages      -- pull out all strings marked for translation
reset             -- executes 'sqlreset' for the given app(s)
runfcgi           -- run this project as a fastcgi
runserver         -- start a lightweight web server for development
shell             -- run a Python interactive interpreter. Tries to use IPython, if it's available
sql               -- print the CREATE TABLE statements for the given app(s)
sqlall            -- print the CREATE TABLE, CREATE INDEX and custom statements for the given app(s)
sqlclear          -- print the DROP TABLE statements for the given app(s)
sqlcustom         -- print the custom table-modifying SQL statements for the given app(s)
sqlflush          -- print the SQL statements required to return all tables to installation state
sqlindexes        -- print the CREATE INDEX statements for the given app(s)
sqlreset          -- print the DROP TABLE and CREATE TABLE statements for the given app(s)
sqlsequencereset  -- print the SQL statements for resetting sequences for the given app(s)
startapp          -- create Django app directory in this project's directory
syncdb            -- create database tables for apps in INSTALLED_APPS where required
test              -- run the test suite for the specified app, or the entire site
testserver        -- run a development server with data from the given fixture(s)
validate          -- validate all installed modules

Create a project

A project is a collection of settings for Django instances, including database configuration, Django specific options, and application specific settings. After the installation is successful, let's start to create a new project TestProject

$ django-admin startproject TestProject

$ cd TestProject
$.
 |____manage.py
 |____TestProject
 | |______init__.py
 | |____settings.py
 | |____urls.py
 | |____wsgi.py

Catalog Description:
TestProject: container for the project.
manage.py : a practical command-line tool that allows you to interact with the Django project in various ways.
TestProject/init.py : an empty file that tells Python that the directory is a Python package.
TestProject/settings.py : settings / configuration of the Django project.
TestProject/urls.py : the URL declaration for the Django project; a Django driven web site "directory.".
TestProject/wsgi.py : an entry to a WSGI compliant Web server to run your project.





Start development server

After the project is created, a Django website can be run. Django comes with a simple network server, which is very convenient in the development process, so we can run the project locally without installing any other software. Start the server by entering the following command in the TestProject project directory:

$ python manage.py runserver 127.0.0.1:8080
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).

You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.

September 27, 2019 - 10:54:32
Django version 2.2.5, using settings 'testweb.settings'
Starting development server at http://127.0.0.1:8080/
Quit the server with CONTROL-C.

The service startup is complete as shown above.
django development services are available during development, a built-in, lightweight web service. It provides a real-time monitoring of your code changes during the website development phase and loading them, so you can directly see the results of the changes without restarting the service.

127.0.0.1: indicates the IP address that can be connected to the server
8080: port number (if not specified, the port number defaults to 8000)

Then input the IP and port number of the server in the browser (here we input the IP address of the local machine: 127.0.0.1:8080). If it is started normally, the output result is as follows:

Note: the development server will reload Python code for each access request if necessary. So you don't need to restart the server frequently for the modified code to take effect. However, some actions, such as adding new files, will not trigger an automatic reload, and you will have to restart the server manually.

Configure development server

Django is a framework that supports internationalization and localization, so the default home page we saw just now also supports internationalization. We change the default language to Chinese, and set the time zone to zone 8. The configuration is as follows:

$ vi TestProject/settings.py
# Omit context
# Set language code
LANGUAGE_CODE = 'zh-hans'
# Set time zone
TIME_ZONE = 'Asia/Chongqing'

Then refresh the previous page, and the page will be displayed in Chinese, as shown in the following figure:

Create an app

After creating the project, you can create applications in the project. Each application is a Python package and follows the same Convention. Django comes with a tool that can help you generate the basic directory structure of your application, so you can concentrate on writing code instead of creating directories.

Project VS application
What's the difference between project and application? An application is a web application that specializes in something - a blog system, a database of public records, or a simple voting program. A project is a collection of configurations and applications used by a website. The project can contain many applications, which can be used by many projects.

Your application can be stored in any path defined in Python path. In this tutorial, we will manage.py Create voting application in the same level directory. This allows it to be imported as a top-level module, not as a sub module of mysite.
Please make sure you are in manage.py Under the directory, run this command to create an application:

$ python manage.py startapp polls
$ tree     #List current directory structure
.
|____db.sqlite3
|____manage.py
|____polls
| |______init__.py
| |____admin.py
| |____apps.py
| |____migrations
| | |______init__.py
| |____models.py
| |____tests.py
| |____views.py
|____TestProject
| |______init__.py
| |______pycache__
| | |______init__.cpython-37.pyc
| | |____settings.cpython-37.pyc
| | |____urls.cpython-37.pyc
| | |____wsgi.cpython-37.pyc
| |____settings.py
| |____urls.py
| |____wsgi.py

Then we can edit the views.py View, operate as follows:

$ vim polls/views.py
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, this is a voting page.")

After saving, exit. This is a simple view. Next, you need to add a route to this view. First of all, we need to create a new one in the poll application urls.py The operation is as follows:

$ vim polls/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
]

After saving, exit, and then you need to modify the urls.py , add the route mapping configuration of poll, as follows:

$ vim TestProject/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]

The function include() allows reference to other URLconfs. Whenever Django encounters include(), it truncates the portion of the URL that matches this and sends the remaining string to URLconf for further processing.
Django's idea of designing include() is to make it plug and play. When including other URL patterns, you should always use include(), admin.site.urls It's the only exception.

Save and exit, then we will visit the website http://localhost:8080/polls/, You can access our newly created page, as shown in the following figure:

summary

In this paper, through the above steps, you can quickly create a website that can be accessed. Do you think it is so simple and convenient to use Django to develop websites. Django also has built-in functions such as templates, forms, routing, authentication, basic database management, etc. next, we will further introduce the advanced functions of Django.

reference resources

Example code: https://github.com/JustDoPython/python-100-day

Pay attention to the official account: python technology, reply to "python", learn and communicate with each other.

Tags: Django Python Database SQL

Posted on Sun, 31 May 2020 23:11:44 -0700 by captainplanet17