文章首发:https://mp.weixin.qq.com/s/S1...
第一个django利用--简略的 hello world 我的项目
前提条件
- python3
- django==2.2
django装置请见:Django疾速装置
留神:django我的项目更适合的是运行在虚拟环境下,不过咱们这里只是学习hello world,为缩小其余因素影响,咱们仅仅应用失常的Python环境(漠然,你也能够应用虚拟环境,如果您会的话)
创立主我的项目
创立
- 关上cmd
- 输出命令:
django-admin startproject hello_world
运行命令会创立一个蕴含一些文件的hello_world文件夹
留神:hello_world是我的项目名,你能够自定义,漠然你能够和我一样
验证
你能够关上cmd,进入hello_world文件夹
而后运行我的项目
python manage.py runserver
失常会显示这样:
August 10, 2020 - 10:11:10Django version 2.2, using settings 'hello_world.settings'Starting development server at http://127.0.0.1:8000/Quit the server with CTRL-BREAK.
你能够在浏览器上关上:
http://127.0.0.1:8000/
像这样:
如果显示失常,那么示意胜利!!!
新建次一级我的项目
- 关上cmd下
- 进入刚刚创立好的我的项目目录(hello_world)下,留神此目录下有一个
manage.py
文件,这个很重要 - 输出命令:
python manage.py startapp my_app
运行命令后,会新增一些文件:
留神:my_app是次一级我的项目名,你能够自定义,漠然你能够和我一样
新增或批改一些文件
上面咱们要新增或批改一些文件,造成咱们的hello world我的项目
因为咱们创立我的项目的门路不肯定是一样的,那么上面我将应用相对路径
批改hello_world\hello_world\settings.py
在列表INSTALLED_APPS新增my_app (用于关联我的项目)
新增文件hello_world\my_app\urls.py
写入一下内容
from django.urls import path,includefrom . import viewsurlpatterns = [ path('',views.home,name='home')]
批改hello_world\my_app\views.py
新增home函数
from django.shortcuts import render,HttpResponse# Create your views here.def home(request): return HttpResponse("hello world")
批改hello_world\hello_world\urls.py
增加urlpattern条目,指向咱们方才建设的my_app这个app独有的urls文件,这里须要导入include模块。
from django.contrib import adminfrom django.urls import path,includeurlpatterns = [ path('admin/', admin.site.urls), path("",include("my_app.urls"))]
批改到这里就完结了
咱们再次运行下我的项目看看
python manage.py runserver
在浏览器上关上:
http://127.0.0.1:8000/
如果返回了一个hello world 示意咱们胜利了
到此,一个简略的hello world 我的项目就完结了,还是比较简单的
关注我获取更多内容