参考:https://www.cnblogs.com/liqu/p/9308966.html
工具
PyCharm
没错就是这么简单!`
创建项目
File-New Project
选择Django,选择项目目录,和Python版本
完事
项目说明
- 项目结构
文件结构说明
--DjangoTest(项目名)
----__init__.py
----settings.py //主配置文件
----urls.py //路由文件,相当于controller
----wsgi.py //网络通信接口
--templates //模板目录
--manage.py //项目管理主程序
-
创建APP
在Terminal中执行python manage.py startapp testapp
生成
testapp
文件夹
-
写个路由试试
在 生成的testapp
目录下的views.py
文件里,添加一个函数# Create your views here. from django.http import HttpResponse def hello(request): return HttpResponse("Hello World!")
之后,在
DjangoTest
目录下的urls.py
里面,添加一个路由from django.contrib import admin from django.urls import path from testapp import views urlpatterns = [ path('admin/', admin.site.urls), #新添加的 path('hello',views.hello) ]
启动项目之后,访问localhost:8000/hello路径,即可看到HelloWorld!
-
返回模板页面
新建一个路由def helloPage(request): context={} context['hello']='Hello!This is context' return render(request,'hello.html',context)
path('helloPage',views.helloPage)
在
templates
目录下新建一个hello.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Test</title> </head> <body> <p>{{ hello }}</p> </body> </html>
访问localhost:8000/helloPage显示
-
配置静态资源路径
当需要使用静态资源,如js,css等时,创建static
目录,并需要在settings.py
中配置配置静态资源路径# Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), 'Djago/static/', ]