本次 Python 版本 2.7.18,Django 1.11.29
参考:Django 的文档 https://yiyibooks.cn/xx/Django_1.11.6/intro/tutorial01.html
安装
pip3 install Django==3.0.6 -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install django
C:\xiaohui\python-u8>pip install django -i https://pypi.tuna.tsinghua.edu.cn/simpleDEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-supportLooking in indexes: https://pypi.tuna.tsinghua.edu.cn/simpleCollecting djangoDownloading https://pypi.tuna.tsinghua.edu.cn/packages/49/49/178daa8725d29c475216259eb19e90b2aa0b8c0431af8c7e9b490ae6481d/Django-1.11.29-py2.py3-none-any.whl (6.9MB)|████████████████████████████████| 7.0MB 376kB/sCollecting pytz (from django)Downloading https://pypi.tuna.tsinghua.edu.cn/packages/d3/e3/d9f046b5d1c94a3aeab15f1f867aa414f8ee9d196fae6865f1d6a0ee1a0b/pytz-2021.3-py2.py3-none-any.whl (503kB)|████████████████████████████████| 512kB 354kB/sInstalling collected packages: pytz, djangoSuccessfully installed django-1.11.29 pytz-2021.3WARNING: You are using pip version 19.2.3, however version 20.3.4 is available.You should consider upgrading via the 'python -m pip install --upgrade pip' command.C:\xiaohui\python-u8>C:\xiaohui\python-u8>pip listDEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-supportPackage Version----------------------------- -------astroid 1.6.6autopep8 1.6.0backports.functools-lru-cache 1.6.4colorama 0.4.4configparser 4.0.2Django 1.11.29enum34 1.1.10futures 3.3.0isort 4.3.21lazy-object-proxy 1.6.0mccabe 0.6.1pip 19.2.3pycodestyle 2.8.0pycparser 2.21pylint 1.9.5pythonnet 2.5.2pytz 2021.3setuptools 41.2.0singledispatch 3.7.0six 1.16.0toml 0.10.2wrapt 1.13.3WARNING: You are using pip version 19.2.3, however version 20.3.4 is available.You should consider upgrading via the 'python -m pip install --upgrade pip' command.
检测安装
django-admin
C:\xiaohui\python-u8>django-admin --version1.11.29C:\xiaohui\python-u8>django-adminType 'django-admin help <subcommand>' for help on a specific subcommand.Available subcommands:[django]checkcompilemessagescreatecachetabledbshelldiffsettingsdumpdataflushinspectdbloaddatamakemessagesmakemigrationsmigraterunserversendtestemailshellshowmigrationssqlflushsqlmigratesqlsequenceresetsquashmigrationsstartappstartprojecttesttestserverNote that only Django core commands are listed as settings are not properly configured (error: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.).C:\xiaohui\python-u8>
或者:使用 python -m django —version
C:\xiaohui\python-u8\demo\web\helloworld>django-admin —version
1.11.29
C:\xiaohui\python-u8\demo\web\helloworld>python -m django —version
1.11.29
创建自己的项目
django-admin startproject helloworld
C:\xiaohui\python-u8\demo\web># 创建 helloworld 项目C:\xiaohui\python-u8\demo\web>django-admin startproject helloworld# 查看目录(其中 __init__.py 是我自己事先建立的,从时间也可以看出来)C:\xiaohui\python-u8\demo\web>dir驱动器 C 中的卷没有标签。卷的序列号是 8C93-6835C:\xiaohui\python-u8\demo\web 的目录2022/02/09 14:23 <DIR> .2022/02/09 14:23 <DIR> ..2022/02/09 14:23 <DIR> helloworld2022/02/09 13:49 0 __init__.py1 个文件 0 字节3 个目录 11,223,138,304 可用字节C:\xiaohui\python-u8\demo\web>cd helloworldC:\xiaohui\python-u8\demo\web\helloworld>dir驱动器 C 中的卷没有标签。卷的序列号是 8C93-6835C:\xiaohui\python-u8\demo\web\helloworld 的目录2022/02/09 14:23 <DIR> .2022/02/09 14:23 <DIR> ..2022/02/09 14:23 <DIR> helloworld2022/02/09 14:23 830 manage.py1 个文件 830 字节3 个目录 11,223,138,304 可用字节C:\xiaohui\python-u8\demo\web\helloworld>cd helloworldC:\xiaohui\python-u8\demo\web\helloworld\helloworld>dir驱动器 C 中的卷没有标签。卷的序列号是 8C93-6835C:\xiaohui\python-u8\demo\web\helloworld\helloworld 的目录2022/02/09 14:23 <DIR> .2022/02/09 14:23 <DIR> ..2022/02/09 14:23 3,229 settings.py2022/02/09 14:23 788 urls.py2022/02/09 14:23 414 wsgi.py2022/02/09 14:23 0 __init__.py4 个文件 4,431 字节2 个目录 11,223,134,208 可用字节C:\xiaohui\python-u8\demo\web\helloworld\helloworld>-----菜鸟教程说明:$ tree.|-- HelloWorld| |-- __init__.py| |-- asgi.py| |-- settings.py| |-- urls.py| `-- wsgi.py`-- manage.py目录说明:HelloWorld: 项目的容器。manage.py: 一个实用的命令行工具,可让你以各种方式与该 Django 项目进行交互。HelloWorld/__init__.py: 一个空文件,告诉 Python 该目录是一个 Python 包。HelloWorld/asgi.py: 一个 ASGI 兼容的 Web 服务器的入口,以便运行你的项目。HelloWorld/settings.py: 该 Django 项目的设置/配置。HelloWorld/urls.py: 该 Django 项目的 URL 声明; 一份由 Django 驱动的网站"目录"。HelloWorld/wsgi.py: 一个 WSGI 兼容的 Web 服务器的入口,以便运行你的项目。
启动服务
python manage.py runserver 0.0.0.0:8000
C:\xiaohui\python-u8\demo\web\helloworld>python manage.py runserver 0.0.0.0:8000Performing system checks...System check identified no issues (0 silenced).You have 13 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 09, 2022 - 15:16:08Django version 1.11.29, using settings 'helloworld.settings'Starting development server at http://0.0.0.0:8000/Quit the server with CTRL-BREAK.[09/Feb/2022 15:17:02] "GET / HTTP/1.1" 200 1716
访问服务 localhost:8000
实战
视图view与URL
先建立 views.py 视图
#!/usr/bin/python# coding=utf-8from django.http import HttpResponsedef sayHello(request):return HttpResponse("hello world")
修改原来 urls.py
"""helloworld URL ConfigurationThe `urlpatterns` list routes URLs to views. For more information please see:https://docs.djangoproject.com/en/1.11/topics/http/urls/Examples:Function views1. Add an import: from my_app import views2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')Class-based views1. Add an import: from other_app.views import Home2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')Including another URLconf1. Import the include() function: from django.conf.urls import url, include2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))"""from django.conf.urls import urlfrom django.contrib import adminurlpatterns = [url(r'^admin/', admin.site.urls),]----------修改为----------"""helloworld URL ConfigurationThe `urlpatterns` list routes URLs to views. For more information please see:https://docs.djangoproject.com/en/1.11/topics/http/urls/Examples:Function views1. Add an import: from my_app import views2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')Class-based views1. Add an import: from other_app.views import Home2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')Including another URLconf1. Import the include() function: from django.conf.urls import url, include2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))"""from django.conf.urls import url# from django.contrib import admin# urlpatterns = [# url(r'^admin/', admin.site.urls),# ]from . import viewsurlpatterns = [url(r'^$', views.sayHello),]
注意,不同版本的 Django url、path 位置不同,当前的 Django 1.11.29 还没搞懂怎么使用 path
在项目下创建自己的应用
python manage.py startapp polls
C:\xiaohui\python-u8\demo\web\helloworld>C:\xiaohui\python-u8\demo\web\helloworld>python manage.py startapp pollsC:\xiaohui\python-u8\demo\web\helloworld>dir驱动器 C 中的卷没有标签。卷的序列号是 8C93-6835C:\xiaohui\python-u8\demo\web\helloworld 的目录2022/02/09 17:15 <DIR> .2022/02/09 17:15 <DIR> ..2022/02/09 15:13 12,288 db.sqlite32022/02/09 16:49 <DIR> helloworld2022/02/09 14:23 830 manage.py2022/02/09 17:15 <DIR> polls2 个文件 13,118 字节4 个目录 11,204,857,856 可用字
需要进入到项目目录里(manage.py 文件所在的目录),然后运行 python manage.py startapp app_name
数据库部分 sqlite
python manage.py migrate
C:\xiaohui\python-u8\demo\web\helloworld>python manage.py migrateOperations to perform:Apply all migrations: admin, auth, contenttypes, sessionsRunning migrations:Applying contenttypes.0001_initial... OKApplying auth.0001_initial... OKApplying admin.0001_initial... OKApplying admin.0002_logentry_remove_auto_add... OKApplying contenttypes.0002_remove_content_type_name... OKApplying auth.0002_alter_permission_name_max_length... OKApplying auth.0003_alter_user_email_max_length... OKApplying auth.0004_alter_user_username_opts... OKApplying auth.0005_alter_user_last_login_null... OKApplying auth.0006_require_contenttypes_0002... OKApplying auth.0007_alter_validators_add_error_messages... OKApplying auth.0008_alter_user_username_max_length... OKApplying sessions.0001_initial... OKC:\xiaohui\python-u8\demo\web\helloworld>python manage.py makemigrations pollsMigrations for 'polls':polls\migrations\0001_initial.py- Create model Choice- Create model Question- Add field question to choiceC:\xiaohui\python-u8\demo\web\helloworld>C:\xiaohui\python-u8\demo\web\helloworld>python manage.py sqlmigrate polls 0001BEGIN;---- Create model Choice--CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL);---- Create model Question--CREATE TABLE "polls_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL);---- Add field question to choice--ALTER TABLE "polls_choice" RENAME TO "polls_choice__old";CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL, "question_id" integer NOT NULL REFERENCES "polls_question" ("id"));INSERT INTO "polls_choice" ("choice_text", "votes", "id", "question_id") SELECT "choice_text", "votes", "id", NULL FROM "polls_choice__old";DROP TABLE "polls_choice__old";CREATE INDEX "polls_choice_question_id_c5b4b260" ON "polls_choice" ("question_id");COMMIT;C:\xiaohui\python-u8\demo\web\helloworld>C:\xiaohui\python-u8\demo\web\helloworld>python manage.py migrateOperations to perform:Apply all migrations: admin, auth, contenttypes, polls, sessionsRunning migrations:Applying polls.0001_initial... OKC:\xiaohui\python-u8\demo\web\helloworld>
python manage.py shell 交互命令,可以执行models 中相关方法 https://yiyibooks.cn/xx/Django_1.11.6/intro/tutorial02.html
管理后台
python manage.py createsuperuser
小结
Django 很强大,mvc,db 都已涉及,好好学习一下。
