python项目之Web应用程序(网页制作篇)

Django2.0环境下

1.映射URL,修改项目主文件夹learning_log中的文件urls.py

1 from django.contrib import admin
2 from django.urls import include, path
3 
4 urlpatterns = [
5     path('admin/',admin.site.urls),  #该模块定义了可在管理网站中请求的所有URL
6     path('',include('learning_logs.urls',namespace = 'learning_logs')),
7 ]

2.在learning_logs中创建另一个urls.py文件

1 from django.urls import include, path
2 from . import views #句点表示让python从当前的urls.py模块所在的文件夹导入视图
3 
4 urlpatterns = [
5     path('',views.index,name = 'index'),  #该模块定义了可在管理网站中请求的所有URL
6 ]
7 
8 app_name = 'learning_logs'

3.编写视图views.py文件

1 from django.shortcuts import render
2 #from django.http import HttpResponse
3 # Create your views here.
4 def index(request):
5     #学习笔记的主页
6      return render(request,'learning_logs/index.html')

4.编写模板index.html,模板定义了网页的结构,可以让你访问视图提供的任何数据

在文件夹learning_logs中新建一个文件夹,并将其命名为templates,在文件夹templates中创建文件夹learning_logs

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8 <p>Learning Log</p>
 9 <p>Learning Log helps you keep track of your learning,for any topic you're learning about.</p>
10 </body>
11 </html>

5.请求项目的基础URL:http://localhost:8000/,将看到刚才创建的网页,而不是默认的Django网页。

Django接受请求的URL,然后调用函数views.index(),将使用index.html包含的模板来渲染网页

运行python manager.py runserver报错:

 

django.core.exceptions.ImproperlyConfigured: Passing a 3-tuple to include() is not supported. Pass a 2-tuple containing the list of patterns and app_name, and provide the namespace argument to include() instead.

解决方法,在urls.py中添加app_name='learning_log'

 

修改之后的运行结果:

 

最终的页面显示如下:

 

 

posted on 2017-12-30 16:20  never1211  阅读(239)  评论(0编辑  收藏  举报

导航