玛克纳尔必须死,政府部门工作总结,梦之队劳资协议书
打开windows cmd输入pip install django
startproject
命令在目录中创建项目
如下图就是通过startproject
命令创建的项目文件结构
项目创建完成后,可通过终端命令runserver
直接启动
#如果有类似异常,可能是django没有安装好,在终端中再重装一次django包(pip install django) traceback (most recent call last): file "manage.py", line 10, in main from django.core.management import execute_from_command_line modulenotfounderror: no module named 'django' the above exception was the direct cause of the following exception: traceback (most recent call last): file "manage.py", line 21, in <module> main() file "manage.py", line 16, in main ) from exc importerror: couldn't import django. are you sure it's installed and available on your pythonpath environment variable? did you forget to activate a virtual environment?
系统检测文件没有问题后,会启动服务
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. june 23, 2019 - 15:57:10 django version 2.2.2, using settings 'hello_world.settings' starting development server at http://127.0.0.1:8000/
然后用浏览器打开http://127.0.0.1:8000/
,能够正常打开页面,说明一切正常
startapp
命令在项目中创建应用包
在shop包中,各文件的说明
在views.py文件中,新增hello()函数
from django.shortcuts import render from django.http import httpresponse # create your views here. def hello(request): return httpresponse("hello world")
增加视图函数之后,我们还需要对路由进行配置,将视图和url进行绑定,不然在网页上是无法浏览到我们添加的视图
首先在shop包中创建一个urls.py路由文件,,这是应用层次的路由配置
from django.urls import path import shop.views urlpatterns = [ path('hello', shop.views.hello) ]
然后还需要对项目层次的路由进行配置,打开hello_world包下的urls.py文件,然后增加path('shop/', include('shop.urls'))
,如果请求地址中含有shop
就转发到刚才配置的shop.urls
路由文件中
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('shop/', include('shop.urls')) ]
打开settings.py
文件,然后进行引用配置(这里配置的方法shopconfig
是在创建应用的时候自动生成的apps.py
文件中的一个方法)
客户请求的过程
现在所有的配置我们已经完成,可以通过runserver
命令启动服务,打开浏览器输入http://127.0.0.1:8000/shop/hello
,到此我们一个基本的helloworld项目已经算是创建完成
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
新手学习Python2和Python3中print不同的用法
Python基于os.environ从windows获取环境变量
网友评论