Statement: the following is my personal understanding. If you find any mistakes or questions, you can contact me for discussion
This tutorial is the second in the Django basic tutorial series. The links to the previous chapters are as follows:
The beginning stage of each project often determines the general trend of the project. In the process of engineering construction, we should make preparations for the later project development.
In order not to be affected by Python environment, it is best to establish a virtual environment and build projects in the virtual environment
virtualenvIs a toolkit for creating Python virtual environment, which can be directly installed through pip
pip3 install virtualenv
virtualenv --python=/usr/bin/python3 django2.2.2_py3
django2.2.2_ PY3 is the name of the virtual environment. Here, it is named after Django version + Python version. Python specifies the location of Python.
After activation, the current virtual environment name will be displayed at the front of the command line
This tutorial uses django2.2.2
pip install django==2.2.2
In Django, the project directory of a project can be created through the commands provided by Django.
The command to create a project is:
Project name of Django admin startproject
For example, if you want to create a demo project when making pasta, you can execute the following command:
cd ~/Desktop/ django-admin startproject demo
After execution, it will be displayed in the current directory
DesktopCreate a directory named demo under the directory, which stores the whole Django project
View the created project directory, and the structure is as follows
(django2.2.2_py3) ~/Desktop/demo$ tree . |-- demo | |-- __init__.py | |-- settings.py | |-- urls.py | `-- wsgi.py `-- manage.py 1 directory, 5 files
- demo: a directory with the same name as the project to store project related files.
- settings.py: configuration file for the project.
- urls.py: the total URL profile of the project.
- wsgi.py: project WSGI compatible web server portal.
- manage.pyProject management file, through which to manage the project, but also the entry to start the project.
In the development stage, in order to quickly preview the effect of development, djnago provides a lightweight web server written in pure python, which can be used in the development stage.
The command to run the server is as follows:
python manage.py runserver
The default IP is 127.0.0.1, and the default port is 8000. You can write the specified IP and port in the format of IP: port
After startup, you can see the following information
(django2.2.2_py3) ~/Desktop/demo$ python manage.py runserver 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. February 17, 2019 - 05:29:56 Django version 2.2.2, using settings 'demo.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C.
Enter the web address “127.0.0.1:8000” in the browser to see the effect.
- Django works in debug mode by default. If files are added, modified or deleted, the server will restart automatically.
- Press Ctrl + C to stop the server.
In web development, a large project is usually composed of numerous applications. Splitting the developing project into different functional modules can make each functional module relatively independent, which is more conducive to our development and management.
Django provides us with the command to create an application
Python manage.py startapp subapplication name
It should be noted that the application must be created in the directory where manage. Py is located
Now create a user related application users, which can perform the following steps:
python manage.py startapp users
After execution, you can see that there is an additional subdirectory named users in the project directory.
(django2.2.2_py3) ~/Desktop/demo$ ls db.sqlite3 demo manage.py users (django2.2.2_py3) ~/Desktop/demo$ tree . |-- db.sqlite3 |-- demo | |-- __init__.py | |-- __pycache__ | | |-- __init__.cpython-36.pyc | | |-- settings.cpython-36.pyc | | |-- urls.cpython-36.pyc | | `-- wsgi.cpython-36.pyc | |-- settings.py | |-- urls.py | `-- wsgi.py |-- manage.py `-- users |-- __init__.py |-- admin.py |-- apps.py |-- migrations | `-- __init__.py |-- models.py |-- tests.py `-- views.py 4 directories, 17 files
- admin.py: background management configuration information.
- apps.py: configuration information.
- migrationsStore the database migration history file.
- models.py: save the database model class.
- tests.py: used to develop test cases and write unit tests.
After creating an application, Django can’t automatically associate the project with the application, so we need to create a project configuration file
settings.pyYou can only use it if you register in.
In project configuration file
settings.pyInINSTALLED_APPSProject is responsible for registration of installed applications, installed in the initial project_ The apps are as follows:
The role of these default applications can be seen in this article:Detailed explanation of Django configuration file
The way to register an application is to add the Config class in app. Py to installed_ Apps list.
For example, you can register the newly created users application in installed_ Add to apps list‘users.apps.UsersConfig’。
The view is used to write the business logic of the application, and the view of Django is in the view.py of the application
Enter the users application and write the view code in views. Py.
from django.http import HttpResponse
Introduction to DjangoAs mentioned in, the function of view in Django is to accept requests, process business, and return responses. Here, the request is the object that receives the request, and the business processing is the generation
hello DjangoString, and httpresponse is the object that returns the response.
In Django, routing is the system that distributes the requested URL to the view.
In general, there are two kinds of route definition locations, one is theProject engineeringIn urls.py, one is in urls.py under each application.Project engineeringURLs. Py is the entry of Django’s parsing route
Route resolution order
Django receives a request from theProject engineeringFind the corresponding routing rules from top to bottom in the urlpatterns list in urls.py. If the rules are included, then enter the urlpatterns list in the included URLs to query from top to bottom.
When defining a route, you can name the route to find the specific path information of a specific view.
When defining the include function to define a route, you can use the namespace parameter to define the route’s namespace, such as
url(r'^users/', include('users.urls', namespace='users')),
The namespace indicates that all routes defined in users.urls belong to the users name specified by the namespace.
The role of the namespace: to avoid conflicts between routes in different applications using the same name, use the namespace to distinguish them.
When defining a normal route, you can use the name parameter to indicate the name of the route, such as
urlpatterns = [ url(r'^index/$', views.index, name='index'), ]
When a route is defined in Django, it usually ends with a slash. The advantage is that when a user accesses the same path that does not end with a slash, Django will redirect the user to the path that ends with a slash / instead of returning 404 does not exist. as
urlpatterns = [ url(r'^index/$', views.index, name='index'), ]
When users visit index or index / Web address, they can access the index view.
Although the slash at the end of the route can bring the above benefits, it violates the design concept of URL indicating the resource location path in http. Whether there is a slash at the end is subject to personal style.
Next, we will connect project, application and view through routing
First of all, at the beginning of the projectTotal routeAdd the routing information of users application in
from django.contrib import admin + from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), + path('users/', include('users.urls')), ]
- ‘users /’ indicates all requests starting with / users /
- Include indicates all routes that are matched to urls.py in users application with / users /, that is, as long as the requested URL starts with / users /, the remaining routes will be matched in urls.py in users application.
After the total route is introduced to the users application, the information of urls.py in the users application needs to be modified
from django.conf.urls import url,re_ path
- Now the complete request URL is / users / index/
After route modification, restart Django program, and you can see the returned information in the browser
This work adoptsCC agreementReprint must indicate the author and the link of this article