1、映射URL
打开项目中learning_log文件夹中的urls.py文件,我的路径:F:\Python\learning_log\learning_log\urls.py
做修改如下:
from django.contrib import admin
from django.urls import path
from django.conf.urls import include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('learning_logs.urls', namespace='learning_logs')), #添加包含模块learning_logs.urls,namespace帮助将URL区分开
]
在learning_logs文件夹下创建另一个urls.py,我的路径:F:\Python\learning_log\learning_logs\urls.py
添加内容如下:
from django.conf.urls import url #导入url函数
from . import views #导入当前文件夹下的views模块
app_name = 'learning_logs'
urlpatterns = [ #列表请求网页
url('', views.index, name='index'), #调用url()
]
2、编写视图
打开learning_logs下的views.py文件,我的路径:F:\Python\learning_log\learning_logs\views.py
添加如下代码:
from django.shortcuts import render #导入render()函数,根据视图提供的数据提供响应
# Create your views here.
def index(request):
return render(request, 'learning_logs\index.html') #主页
3、编写模板
视图主页路径为learning_logs\index.html,创建这个文件,具体操作:
在learning_logs下创建一个名为templates的文件夹,在其中新建learning_logs文件夹,在此文件夹下创建index.html文件
我的路径:F:\Python\learning_log\learning_logs\templates\learning_logs\index.html
内容如下:
<p>Learning Log</p>
<p>Learning Log helps you keep track of your learning, for any topic you're learning about.</p>
打开虚拟环境,运行runserver, 打开浏览器本地IP地址,端口8000,可以看到index.html中编辑的内容