location 最后一个文件夹名就是 project 名,我用了 Django_Plan。
Application 是自动加入的 APP 名字,我用了 Plan
编辑 Django_Plan\Django_Plan\urls.py
- from django.contrib import admin
- from django.urls import path
- from Plan import views
- urlpatterns = [
- path('admin/', admin.site.urls),
- path('plan', views.plan) #此行为增加的
- ]
编辑 Django_Plan\Plan\views.py
- from django.shortcuts import render
- from django.shortcuts import HttpResponse #此行增加
- # Create your views here.
- def plan(request): #此函数增加
- return HttpResponse('hello')
好了,我们增加了一个 url 解析,解析到 plan 函数,进行 http 返回给浏览器。
试一下,浏览器 http://localhost:8000/plan,会看到 hello。用的是 HttpResponse 函数。
平时访问的页面那么多内容,我们不能都写在 HttpResponse 中呀。
我们用模板吧。建立一个 hello.html 文件放在 Django_Plan\templates\hello.html
内容为:
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Hello</title>
- </head>
- <body>
- <h1>hello</h1>
- </body>
- </html>
编辑 Django_Plan\Plan\views.py
检查 Django_Plan\Django_Plan\settings.py(难道我用最新的 django2.0,pycharm 就不自动创建了?)
- from django.shortcuts import render
- from django.shortcuts import HttpResponse #此行增加
- # Create your views here.
- def plan(request): #此函数增加
- return render(request,'hello.html')
好了,这下浏览器返回的就是我们的模板文件内容,h1 格式的 hello
- TEMPLATES = [
- {
- 'BACKEND': 'django.template.backends.django.DjangoTemplates',
- 'DIRS': [os.path.join(BASE_DIR,'templates')], #注意此行
- 'APP_DIRS': True,
- 'OPTIONS': {
- 'context_processors': [
- 'django.template.context_processors.debug',
- 'django.template.context_processors.request',
- 'django.contrib.auth.context_processors.auth',
- 'django.contrib.messages.context_processors.messages',
- ],
- },
- },
- ]
我们还需要动态生成页面,继续编辑 hello.html, 给输出的 hello 加上两个大括号
编辑 Django_Plan\Plan\views.py
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Hello</title>
- </head>
- <body>
- <h1>{{ hello }}</h1>
- </body>
- </html>
- from django.shortcuts import render
- from django.shortcuts import HttpResponse #此行增加
- # Create your views here.
- def plan(request): #此函数增加
- return render(request,'hello.html',{'hello':'hello jack'})
这里就是在 render 的参数中又加了一个字典,把 hello 换成 hello jack,再返回给客户端浏览器。
打开页面试试吧。
来源: http://www.bubuko.com/infodetail-2438252.html