Django demo project construction

Install Django

In application development, create env folder and wordspace folder respectively.

The env folder is used to store the created virtual environment, and wordspace is used to store the project code. This achieves the separation of the virtual environment and application code.

Step 1: Create a folder and the creation commands are mkdir env and mkdir wordspace.

Step 2: Install virtualenv library. The creation command is pip install virtualenv.

Step 3: Switch to the env folder and move the command to create a virtual environment. The creation command is virtualenv --no-site-pack-ages -p C:\Users\a-xiaobodou\AppData\Local\Programs\Python\Python310\python.exe study_env.

 document:

Check the help of virtualenv. The creation command is: virtualenv --help

PS C:\Users\a-xiaobodou\OneDrive - Microsoft\Projects\Python\env> virtualenv --help
usage: virtualenv [--version] [--with-traceback] [-v | -q] [--read-only-app-data] [--app-data APP_DATA] [--reset-app-data] [--upgrade-embed-wheels] [--discovery {builtin}] [-p py] [--try-first-with py_exe]
                  [--creator {builtin,cpython3-win,venv}] [--seeder {app-data,pip}] [--no-seed] [--activators comma_sep_list] [--clear] [--no-vcs-ignore] [--system-site-packages] [--copies] [--no-download | --download]
                  [--extra-search-dir d [d ...]] [--pip version] [--setuptools version] [--wheel version] [--no-pip] [--no-setuptools] [--no-wheel] [--no-periodic-update] [--symlink-app-data] [--prompt prompt] [-h]
                  dest

options:
  --version                     display the version of the virtualenv package and its location, then exit
  --with-traceback              on failure also display the stacktrace internals of virtualenv (default: False)
  --read-only-app-data          use app data folder in read-only mode (write operations will fail with error) (default: False)
  --app-data APP_DATA           a data folder used as cache by the virtualenv (default: C:\Users\a-xiaobodou\AppData\Local\pypa\virtualenv)
  --reset-app-data              start with empty app data folder (default: False)
  --upgrade-embed-wheels        trigger a manual update of the embedded wheels (default: False)
  -h, --help                    show this help message and exit

verbosity:
  verbosity = verbose - quiet, default INFO, mapping => CRITICAL=0, ERROR=1, WARNING=2, INFO=3, DEBUG=4, NOTSET=5

  -v, --verbose                 increase verbosity (default: 2)
  -q, --quiet                   decrease verbosity (default: 0)

discovery:
  discover and provide a target interpreter

  --discovery {builtin}         interpreter discovery method (default: builtin)
  -p py, --python py            interpreter based on what to create environment (path/identifier) - by default use the interpreter where the tool is installed - first found wins (default: [])
  --try-first-with py_exe       try first these interpreters before starting the discovery (default: [])

creator:
  options for creator builtin

  --creator {builtin,cpython3-win,venv}
                                create environment via (builtin = cpython3-win) (default: builtin)
  dest                          directory to create virtualenv at
  --clear                       remove the destination directory if exist before starting (will overwrite files otherwise) (default: False)
  --no-vcs-ignore               don't create VCS ignore directive in the destination directory (default: False)
  --system-site-packages        give the virtual environment access to the system site-packages dir (default: False)
  --copies, --always-copy       try to use copies rather than symlinks, even when symlinks are the default for the platform (default: True)

seeder:
  options for seeder app-data

  --seeder {app-data,pip}       seed packages install method (default: app-data)
  --no-seed, --without-pip      do not install seed packages (default: False)
  --no-download, --never-download
                                pass to disable download of the latest pip/setuptools/wheel from PyPI (default: True)
  --download                    pass to enable download of the latest pip/setuptools/wheel from PyPI (default: False)
  --extra-search-dir d [d ...]  a path containing wheels to extend the internal wheel list (can be set 1+ times) (default: [])
  --pip version                 version of pip to install as seed: embed, bundle or exact version (default: bundle)
  --setuptools version          version of setuptools to install as seed: embed, bundle or exact version (default: bundle)
  --wheel version               version of wheel to install as seed: embed, bundle or exact version (default: bundle)
  --no-pip                      do not install pip (default: False)
  --no-setuptools               do not install setuptools (default: False)
  --no-wheel                    do not install wheel (default: False)
  --no-periodic-update          disable the periodic (once every 14 days) update of the embedded wheels (default: False)
  --symlink-app-data            not supported - symlink the python packages from the app-data folder (requires seed pip>=19.3) (default: False)

activators:
  options for activation scripts

  --activators comma_sep_list   activators to generate - default is all supported (default: bash,batch,fish,nushell,powershell,python)
  --prompt prompt               provides an alternative prompt prefix for this environment (value of . means name of the current working directory) (default: None)

config file C:\Users\a-xiaobodou\AppData\Local\pypa\virtualenv\virtualenv.ini missing (change via env var VIRTUALENV_CONFIG_FILE)
PS C:\Users\a-xiaobodou\OneDrive - Microsoft\Projects\Python\env>

The creation command is: virtualenv -p C:\Users\a-xiaobodou\AppData\Local\Programs\Python\Python310\python.exe study_env

PS C:\Users\a-xiaobodou\OneDrive - Microsoft\Projects\Python\env> virtualenv -p C:\Users\a-xiaobodou\AppData\Local\Programs\Python\Python310\python.exe study_env
created virtual environment CPython3.10.7.final.0-64 in 7284ms
  creator CPython3Windows(dest=C:\Users\a-xiaobodou\OneDrive - Microsoft\Projects\Python\env\study_env, clear=False, no_vcs_ignore=False, global=False)
  seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=C:\Users\a-xiaobodou\AppData\Local\pypa\virtualenv)
    added seed packages: pip==22.3.1, setuptools==65.6.3, wheel==0.38.4
  activators BashActivator,BatchActivator,FishActivator,NushellActivator,PowerShellActivator,PythonActivator
PS C:\Users\a-xiaobodou\OneDrive - Microsoft\Projects\Python\env>

 document:

 Step 3: Activate the virtual environment. Enter the virtual environment "study_env/Scripts" folder and execute the activate command to activate the current virtual environment study_env.

Step 4: Install Djiango. The installation command is pip install django.

Step 5: Check whether Djiango can be used normally.

PS C:\Users\a-xiaobodou\OneDrive - Microsoft\Projects\Python\env\study_env\Scripts> python
Python 3.10.7 (tags/v3.10.7:6cc6b13, Sep  5 2022, 14:08:36) [MSC v.1933 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> django.VERSION
(4, 1, 4, 'final', 0)
>>>

 Step three, solved. Required to be an administrator.

Step four: 

document:

 Command Line:

Microsoft Windows [Version 10.0.22000.1219]
(c) Microsoft Corporation. All rights reserved.

C:\Windows\system32>cd C:\Users\a-xiaobodou\OneDrive - Microsoft\Projects\Python\env\study_env\Scripts

C:\Users\a-xiaobodou\OneDrive - Microsoft\Projects\Python\env\study_env\Scripts>activate study_env

(study_env) C:\Users\a-xiaobodou\OneDrive - Microsoft\Projects\Python\env\study_env\Scripts>pip install django
Collecting django
  Using cached Django-4.1.4-py3-none-any.whl (8.1 MB)
Collecting sqlparse>=0.2.2
  Using cached sqlparse-0.4.3-py3-none-any.whl (42 kB)
Collecting asgiref<4,>=3.5.2
  Using cached asgiref-3.5.2-py3-none-any.whl (22 kB)
Collecting tzdata
  Using cached tzdata-2022.7-py2.py3-none-any.whl (340 kB)
Installing collected packages: tzdata, sqlparse, asgiref, django
Successfully installed asgiref-3.5.2 django-4.1.4 sqlparse-0.4.3 tzdata-2022.7

(study_env) C:\Users\a-xiaobodou\OneDrive - Microsoft\Projects\Python\env\study_env\Scripts>

Step five:

First Django project

1. Interpretation of creating projects and the functions of each file

Djiangorjwa's django-admin command can help us quickly build the project.

Step 1: Activate the virtual environment study_env

Step 2: Enter the code storage folder wordspace and create a Djiango project named "hello". The command is django-admin startproject hello.

 Command Line:

(study_env) C:\Users\a-xiaobodou\OneDrive - Microsoft\Projects\Python>cd wordspace

(study_env) C:\Users\a-xiaobodou\OneDrive - Microsoft\Projects\Python\wordspace>django-admin startproject hello

(study_env) C:\Users\a-xiaobodou\OneDrive - Microsoft\Projects\Python\wordspace>

Step 3: View the directory structure.

 File 1

File 2

 visual studio code:

(1) __init__.py: Indicates that the directory structure is a Python package that can initialize the database.

(2) settings.py: Represents the configuration file of the Django project, which can configure the data inventory, static resources, debugging mode, domain name restrictions and other configuration information used by the project.

(3) urls.py: Represents the URL routing mapping file of the project.

(4) wsgi.py: Represents the defined WSGI interface information.

(5) manage.py: Represents the management set tool file, which is used to start the entire Django project.

2. Creation of applications and interpretation of the functions of each file

Application apps are mainly used to process business logic, such as the implementation of models, views, routing and other functions.

Step 1: Enter the hello project folder and execute the application creation command. The command is python manage.py startapp app_name

Command Line:

(study_env) C:\Users\a-xiaobodou\OneDrive - Microsoft\Projects\Python\wordspace\hello>python manage.py startapp app_name

(study_env) C:\Users\a-xiaobodou\OneDrive - Microsoft\Projects\Python\wordspace\hello>

Step 2: Directory Structure

(1) Migrations: Represents intermediate files used to store database changes when executing migration commands.

(2) admin.py: Represents the file used to configure the management model in the management background.

(3) apps.py: used to add INSTALLED_APPS to the project directory settings.py.

(4) models.py: Represents the file used to define the database table model. This file is the module embodied by M in MVT.

(5) tests.py: Represents the file used to write unit tests.

(6) views.py: Represents the code file used to define the view function. This file is the module embodied by V in MVT.

3. Start the project

Step 1: Edit the "" file and add the name of the application app_name in INSTALLED_APPS.

INSTALLEND_APPS=[
    ......
    'app',    #新增此行
]

Step 2: Enter the startup command in the console. The command is python manage.py runserver 0.0.0.0:8080 to start the server.

Line of code:

(study_env) C:\Users\a-xiaobodou\OneDrive - Microsoft\Projects\Python\wordspace\hello>python manage.py runserver 0.0.0.0:8080
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).

You have 18 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.
December 13, 2022 - 16:46:26
Django version 4.1.4, using settings 'hello.settings'
Starting development server at http://0.0.0.0:8080/
Quit the server with CTRL-BREAK.
[13/Dec/2022 16:47:19] "GET / HTTP/1.1" 200 10681
[13/Dec/2022 16:47:20] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423
[13/Dec/2022 16:47:20] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 200 86184
[13/Dec/2022 16:47:20] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 85692
[13/Dec/2022 16:47:20] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 85876
Not Found: /favicon.ico
[13/Dec/2022 16:47:20] "GET /favicon.ico HTTP/1.1" 404 2109

0.0.0.0 in the startup command means that the project can be accessed by computers in the same LAN, and 8080 represents the port number.

If the port is not specified and the startup command is python manage.py runserver, it means that port 8000 is opened by default.

Note: You can write both IP and port parameters in the startup command, such as the command: python manage.py runserver IP:port; you can also write only the port, such as the command: python manage.py runserver port, which means the local IP address is started by default. That is 127.0.0.1.

Step 3: Enter the IP address and port number in the browser, such as http://127.0.0.1:8080. If the page looks like the picture below, it means that the Django project has been started successfully.

Routing configuration and view usage 

The view layer in Django is mainly used to process HTTP requests and perform business logic processing, and finally respond to related HTML templates. The view layer receives HTTP requests and maps them to the corresponding business logic functions in the view layer, which requires the use of a URL mapping mechanism. The URL mapping mechanism requires attention to routing configuration and view definition.
The URL mapping mechanism in routing configuration
Django is mainly reflected in the urls.py file, so you need to edit the urls.py file. Configure the routing address hello/' in the urlpatterns variable. When the reader accesses this address in the browser, the program will call the hello() view function defined in app_name/views.py for view processing.

The code of hello/urls.py is as follows:

"""hello URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path

from app_name import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('hello/', views.hello),
]

View definition:

When defining the function hello() in the app_name/views.py file, you need to pay attention to the following two points.

(1) Take request as the first parameter. There are many methods in request. For example, to determine the current HTTP request method, you can use request.method to obtain it.

(2) The view function must have a return value. HttpResponse is used to return HTTP content, render is used to render the page, and redirect or HttpResponseRedirect is used for redirection.

Define the hello() function in views.py of application app_name, the code is as follows:

from django.shortcuts import render

# Create your views here.

from django.http import HttpResponse

def hello(request):
    if request.method=='GET':
        return HttpResponse('Hello Python!')

URL mapping and corresponding view functions have been configured successfully. Access the address http://127.0.0.1:8000/hello/ in the browser.
Movement results failed.

Guess you like

Origin blog.csdn.net/DXB2021/article/details/128301297
Recommended